曲径通幽论坛

标题: const_cast -- 去掉 const 或 volatile 属性 [打印本页]

作者: beyes    时间: 2011-12-6 14:02
标题: const_cast -- 去掉 const 或 volatile 属性
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 属性会带来潜在的危险,所以应该谨慎使用哦这个运算符。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2