题
我找不到多少信息 const_cast
.唯一的信息,我能找到的(关于堆叠的溢出)是:
的
const_cast<>()
是用来增加/删除const(斯)(或挥发性)的一个变量。
这让我紧张。可以使用 const_cast
会导致意外的行为?如果是这样,什么?
或者,当时是不是好用 const_cast
?
解决方案
const_cast
是安全的,只有如果你铸造一个可变的,最初是非const
.例如,如果你有一个功能,需要一个参数的一个 const char *
, 和你通过在可修改 char *
, 它是安全的 const_cast
该参数回到一个 char *
和修改。但是,如果原始变量是事实上 const
, 然后使用 const_cast
会导致不确定的行为。
void func(const char *param, size_t sz, bool modify)
{
if(modify)
strncpy(const_cast<char *>(param), sz, "new string");
printf("param: %s\n", param);
}
...
char buffer[16];
const char *unmodifiable = "string constant";
func(buffer, sizeof(buffer), true); // OK
func(unmodifiable, strlen(unmodifiable), false); // OK
func(unmodifiable, strlen(unmodifiable), true); // UNDEFINED BEHAVIOR
其他提示
我可以想到的两种情况下,const_cast是安全和有益(可能有其他效情况下)。
一种是当你有一个常量实例,参考,或指针,并且要传递一个指或参考API不是const-正确,但你肯定不会修改的对象。你可以const_cast指针,并通过它向API,相信,它不会真正改变任何东西。例如:
void log(char* text); // Won't change text -- just const-incorrect
void my_func(const std::string& message)
{
log(const_cast<char*>(&message.c_str()));
}
其他的是如果您使用的旧编译器,不执行'可变的',你想要建立一个类,在逻辑上是常量但没有按位const。你可以const_cast'这个'内的一个常量的方法和修改的成员。
class MyClass
{
char cached_data[10000]; // should be mutable
bool cache_dirty; // should also be mutable
public:
char getData(int index) const
{
if (cache_dirty)
{
MyClass* thisptr = const_cast<MyClass*>(this);
update_cache(thisptr->cached_data);
}
return cached_data[index];
}
};
我觉得很难相信这是的 只 信息你能找到关于const_cast.引述 第二谷歌打:
如果你抛弃constness的 目的,已经明确 宣布为常量,并试图 修改,结果是不确定的。
但是,如果你抛弃 constness的对象,没有 已经明确地宣布,作为常量,你 可以修改它的安全。
什么亚当说。另一个例子,其中const_cast可以有所帮助:
struct sample {
T& getT() {
return const_cast<T&>(static_cast<const sample*>(this)->getT());
}
const T& getT() const {
/* possibly much code here */
return t;
}
T t;
};
我们第一次加const的类型 this
点,那么我们呼const版本的 getT
, 然后我们删除const从返回的类型,这是有效的,因为 t
必须非常量(否则,非常量版的 getT
已经不能叫).这可能是非常有用的,如果你有了一个大功能的身体,你想要避免的冗余的代码。
简短的回答是否定的,这不是安全的。
长的答复是,如果你知道的足够使用,那么它应该是安全的。
当你铸造的,什么你基本上都是说"我知道的东西编译器不知道。" 在这种情况下的const_cast,什么你是说是,"即使这种方法需要在一个非常量基准或指针,我知道这不会改变的参数我通过它。"
所以如果你这样做实际上知道你是什么声称知道在使用铸塑,然后可以使用它。
你摧毁任何机会在线安全,如果你开始修改的东西,编译器的想法是const。
#include <iostream>
using namespace std;
void f(int* p) {
cout << *p << endl;
}
int main(void) {
const int a = 10;
const int* b = &a;
// Function f() expects int*, not const int*
// f(b);
int* c = const_cast<int*>(b);
f(c);
// Lvalue is const
// *b = 20;
// Undefined behavior
// *c = 30;
int a1 = 40;
const int* b1 = &a1;
int* c1 = const_cast<int*>(b1);
// Integer a1, the object referred to by c1, has
// not been declared const
*c1 = 50;
return 0;
}