曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4533|回复: 0
打印 上一主题 下一主题

const_cast -- 去掉 const 或 volatile 属性

[复制链接]

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
跳转到指定楼层
楼主
发表于 2011-12-6 14:02:29 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
const_cast 用来显式的去掉变量的 const 或者 volatile 属性。

在这种强制转换运算中,目标类型与源类型必须是一致的,只是源类型中的 const 或 volatile 属性在目标类型中被去掉了。一般情况下,我们大部分时候会用 const_cast 去掉 const 属性,其通用形式如下:
const_cast <type> (expr)

其中 type 指定了强制类型转换的目标类型,expr 是需要进行强制转换的表达式。

测试代码1
[C++] 纯文本查看 复制代码
#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    
    int i = 10;
    const int *v = &i;
    int *p;


    p = const_cast <int *> (v);


    *p = 15;
    
    cout << i << endl;
    return 0;
}

上面,声明了 const int * 指针变量 v ,注意不能认为 const_cast<int *> (v) 是去掉 v 这个变量本身的 const 属性,也就是说下面的用法是错误的:
v = const_cast <int *> (v);
*v = 15;

测试代码2:
[C++] 纯文本查看 复制代码
#include "stdafx.h"
#include <iostream>
using namespace std;


void func(const int *p)
{
    int *v;


    //去掉 const 属性
    v = const_cast<int *> (p);


    *v = 100;    //现在可以通过指针v来修改值了
}
int _tmain(int argc, _TCHAR* argv[])
{
    
    int x = 99;
    cout << "x before call: " << x << endl;


    func(&x);
    
    cout << "x after call: " << x << endl;
    
    return 0;
}

运行输出:
x before call: 99
x after call: 100
从上面看到,虽然函数 func() 中的参数是一个 const 指针,但仍然可以在函数体内修改变量的值。

需要强调的是:使用 const_cast 来去掉 const 属性会带来潜在的危险,所以应该谨慎使用哦这个运算符。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-17 08:58 , Processed in 0.076594 second(s), 24 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表