A转换的C样式转换可以处理,但C ++转换不能 [英] A conversion that C-style cast can handle, but C++ casts cannot
问题描述
据说是C样式转换只是试图适用的C ++铸件不同组合和使用第一允许组合。不过,我有听说有只C样式转换可以处理的情况下,虽然没有C ++的类型转换的组合被允许的感觉。
It is said that C-style cast just tries to apply different combination of C++ casts and the first allowed combination is used. However, I have a feeling that I heard that there are situations that only C-style cast can handle, while none of combination of C++ casts are allowed.
难道我错了吗?那是真的,任何的C风格的铸造的任何的情况下(在C ++)能够与C ++类型转换的适当的组合来代替?
Am I wrong? Is that true that any C-style cast in any context (in C++) can be replaced with a proper combination of C++ casts?
UPD 感谢欢呼和心连心。 - 阿尔夫,我们有一个例子,C ++转换不能在它们不能产生的定义的和的有望的行为的意义处理。先进的问题是提供C ++转换不能处理意甚的编译它不可能是一个例子的?
UPD Thanks to Cheers and hth. - Alf, we have an example that C++ casts cannot handle in the meaning they cannot produce defined and expected behavior. Advanced question is to provide an example which C++ casts cannot handle meaning it cannot be even compiled?
推荐答案
投放到人迹罕至的基础只能是pssed为C风格的类型转换(语法变种之一)前$ P $。在这种情况下它相当于一个的static_cast
,这可能更改地址,但的static_cast
无法访问基地。
Cast to inaccessible base can only be expressed as a C style cast (one of the syntactic variants). In that context it is equivalent to a static_cast
, which may change the address, except that static_cast
can't access the base.
例如:
struct Base
{
int x = 42;
};
struct Oh_my
: private Base
{
virtual ~Oh_my() {}
};
#include <iostream>
using namespace std;
auto main() -> int
{
Oh_my o;
cout << "C cast: " << ((Base&)o).x << endl;
cout << "reinterpret_cast: " << reinterpret_cast<Base&>(o).x << endl;
}
在Windows 7中使用MinGW的g ++输出:
Output with MingW g++ in Windows 7:
C cast: 42
reinterpret_cast: 4935184
但因为它是pretty未定义行为,最后输出操作可能只是崩溃。
But since it's pretty Undefined Behavior, the last output operation could just crash.
这篇关于A转换的C样式转换可以处理,但C ++转换不能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!