A conversion that C-style cast can handle, but C++ casts cannot

萝らか妹 提交于 2019-12-18 22:32:26

问题


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.

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 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?


回答1:


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.

Example:

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;
}

Output with MingW g++ in Windows 7:

C cast: 42
reinterpret_cast: 4935184

But since it's pretty Undefined Behavior, the last output operation could just crash.



来源:https://stackoverflow.com/questions/33899978/a-conversion-that-c-style-cast-can-handle-but-c-casts-cannot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!