c++的const_cast

c++的const_cast操作符是给一个变量删除增加 constvolatile 修饰,例如:

const int a = 10;
int &b = const_cast<int&>(a);
// 注意:这里任何b=xxx的操作都会导致为定义行为的发生!
//     因为a原始定义的时候就是const类型.

或:

void func(const int &c) {
    int &d = const_cast<int&>(c);
    d = 20; // 这里修改是ok的,因为c原始定义并不是const类型
            // 只是在函数传参时才变成"const"的
}

int main(void) {
    int c = 10;
    func(c);
}

对const_cast<>的变量进行修改操作只有在原始变量不是真正的const情况下是安全的, 如果原始变量是const类型,那么任何修改都会导致为定义行为。

const_cast is safe only if you’re casting a variable that was originally non-const.

Leave a Comment


*


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>