C ++ const_cast用法而不是C风格的转换 [英] C++ const_cast usage instead of C-style casts
问题描述
为什么是以下内容:
const int i0 = 5;
//int i1 = const_cast<int>(i0); // compilation error
int i2 = (int)i0; // okay
int i3 = 5;
//const int i4 = const_cast<const int>(i3); // compilation error
const int i5 = (const int)i3; // okay
推荐答案
const int i0 = 5;
//int i1 = const_cast<int>(i0); // compilation error
int i2 = (int)i0; // okay
int i3 = 5;
//const int i4 = const_cast<const int>(i3); // compilation error
const int i5 = (const int)i3; // okay
编译错误是因为你不强制const / add const。相反,你复制i0。对于该操作,根本不需要转换:
The compilation errors are caused because you don't cast const away/add const. Instead, you copy i0. For that operation, no cast is required at all:
int i1 = i0;
const int i4 = i3;
你转换的类型实际上应该是一个指针或引用。否则,使用const_cast没有意义,因为你可以直接复制它。例如,对于指针,可以抛弃const,因为取消引用指针将为 const T *
产生另一个类型(产生 const T
) T *
(产生 T
)。对于引用,同样是真的: T&
将使用另一个 this 指针类型访问对象,而不是使用 const T&
。现在你真正想要归档:
The type you cast to should actually be a pointer or reference. Otherwise, using const_cast doesn't make sense since you could straight copy it. For pointers, for example, you can cast away the const, because dereferencing the pointer will yield another type for a const T*
(yields const T
) than for a T*
(yields T
). For references, the same is true: T&
will access the object using another this pointer type than using const T&
. Now what you really wanted to archive:
const int i0 = 5;
//int & i1 = const_cast<int&>(i0); // okay (but dangerous)
int & i2 = (int&)i0; // okay (but dangerous)
int i3 = 5;
//const int&i4 = const_cast<const int&>(i3); // ok now and valid!
const int&i5 = (const int&)i3; // okay too!
上面的例子可能导致未定义的行为,当你写一个原来的const对象通过引用非-const(实际上,只是转换和读取它本身不是未定义的行为,但如果你抛弃const,你也可以写它,然后产生未定义的行为)
The above can lead to undefined behavior, when you write to an originally const object through a reference to non-const (actually, merely casting and reading it isn't undefined behavior in itself. But if you're casting away const, you may also write to it, which then yields the undefined behavior)
这篇关于C ++ const_cast用法而不是C风格的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!