开发者

Requirement for explicit type conversion

For static_cast, Is it true that, unless there exist a built-in type conversion function, you cannot use static_cast to perform conve开发者_如何学编程rsion. But you can do a reinterpret_cast for a type, considering the return type is valid.

int main()
{
    WORD word;
    HWND hwnd = static_cast<HWND>(word); // error
    HWND hwnd = reinterpret_cast<HWND>(word); // ok, considering a valid handle is returned.
}

Do the explicit type conversions done with static_cast require a conversion function unlike reinterpret_cast?


reinterpret_cast just allows you to convert completely unrelated types. It just treats the chunk of memory as another type. So it is very unsafe to use it, since it just doesn't give you any compile or runtime errors but just causes (usually) crash

static_cast provides compile time check of validity of an cast. If an type cannot be treated as another type then static_cast gives you an compile time error when attempting an cast. It does implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).

So you can say that it can do the implicit casts for which there is an implicit conversion inbuilt function present. It is usually considered as replacement for c-style casting if that is the confusion.


The C++ casts make most sense when casting pointers and references.

Concrete examples

void foo (Base & b) {
    if (b .is_a_Foo ())
        static_cast <Foo &> (b) .bar ();
    else
        b .do_default_bar ();
    dynamic_cast <Baz &> (b) .something (); // throws if invalid conversion
}

char data [4];
* reinterpret_cast <float *> (data) = 1.23;

The Windows API is a horrible hack from top to bottom -- in your example, reinterpret_cast is faithful to the original intent (and highlights it for the world to admire) and it basically means "throw away the type system and use the raw bits: trust me".


Basically static_cast allocates memory for compatible class size of destination type and fills it with what is possible, but without any checking that new object is complete. Let me give you an example:

class A {
public:
    int a;
};

class B : public A {
public:
    int c;
    int b;
};

int main()
{
    A *a = new A;
    a->a = 5;
    B *b = new B;
    b->a = 6;
    b->b = 7;
    b->c = 8;

    B* bb = static_cast<B*>(a);
    A* aa = static_cast<A*>(b);

    cout << bb->a << endl; // 5
    cout << bb->b << endl; // scrap value from memory
    // member b was not initialized, because it was not found in A

    cout << aa->a << endl; // 6

    return 0;
}

In your example static cast is invalid, because hwnd is void * and word is unsigned short. For c++ casts any type can be considered as a class;

reinterpret_cast works always. It is just a binary copy

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜