简体   繁体   中英

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

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM