const_cast conversion
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
不同的简历,资格类型之间转换.
原文:
Converts between types with different cv-qualification.
目录 |
[编辑] 语法
const_cast < new_type > ( expression )
|
|||||||||
返回值类型
new_type
[编辑] 解释
只有下面的转换可以做const_cast。尤其是,仅可用于const_cast抛弃(删除)常量性或波动性.
原文:
Only the following conversions can be done with const_cast. In particular, only const_cast may be used to cast away (remove) constness or volatility.
1)
两个可能相同类型的多级指针可以相互间的转换,不管cv修饰符在每个级别.
原文:
Two possibly multilevel pointers to the same type may be converted between each other, regardless of cv-qualifiers at each level.
2)
任何类型的
T
左值可能会被转换到一个左值或rvalue引用到相同类型T
,更多或更少的cv限定。同样地,一个rvalue可被转换成一个或多或少cv限定rvalue引用.原文:
lvalue of any type
T
may be converted to a lvalue or rvalue reference to the same type T
, more or less cv-qualified. Likewise, an rvalue may be converted to a more or less cv-qualified rvalue reference.3)
规则同样适用于可能是多层次的数据成员的指针.
原文:
Same rules apply to possibly multilevel pointers to data members.
4)
空指针值可转换为空指针值的new_type
原文:
null pointer value may be converted to the null pointer value of new_type
与所有的强制转换表达式,其结果是:
原文:
As with all cast expressions, the result is:
- 如果一个左值new_type是一个左值引用类型或一个右值引用为函数类型原文:an lvalue if new_type is an lvalue reference type or an rvalue reference to function type;
- 值为xValue,如果new_type是一个右值引用的对象类型原文:an xvalue if new_type is an rvalue reference to object type;
- 一个prvalue否则.
[编辑] 注释
函数指针和成员函数的指针是不受到const_cast
原文:
Pointers to functions and pointers to member functions are not subject to const_cast
即使const_cast可以删除任何指针常量性或参考,使用指针或引用写的对象被宣布const调用未定义的行为.
原文:
Even though const_cast may remove constness from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const invokes undefined behavior.
[编辑] 关键字
[编辑] 示例
#include <iostream> struct type { type() :i(3) {} void m1(int v) const { // this->i = v; // compile error: this is a pointer to const const_cast<type*>(this)->i = v; // OK } int i; }; int main() { int i = 3; // i is not declared const const int& cref_i = i; const_cast<int&>(cref_i) = 4; // OK: modifies i std::cout << "i = " << i << '\n'; type t; t.m1(4); std::cout << "type::i = " << t.i << '\n'; const int j = 3; // j is declared const int* pj = const_cast<int*>(&j); *pj = 4; // undefined behavior! void (type::*mfp)(int) const = &type::m1; // pointer to member function // const_cast<void(type::*)(int)>(mfp); // compiler error: const_cast does not // work on function pointers }
输出:
i = 4 type::i = 4