开发者

C++ - Casting void pointer

Does C++ throw runtime exceptions when you try to cast a void* to something that it isn't?

class Sheep
{
public:
    Sheep() { }

    ~Sheep() { }

    void Bah()
    {
        // Print Bah!
    }
};

class Unicorn
{
    Unicorn() { }

    ~Unicorn() { }

    void Stab(Sheep* s)
    {
        s->Bah();
    }
};


int main()
{
    Sheep sheep;

    void* ptr = (void*) &s;

    开发者_开发技巧// I'm guessing this would be 'valid'
    Unicorn* unicorn = (Unicorn*) ptr;
    // This must go wrong..?
    unicorn->Stab(&sheep);

    return 0;
} 


Does C++ throw runtime exceptions when you try to cast a void* to something that it isn't?

No, it doesn't.

The behavior of your program is undefined: anything could happen. The program might appear to work most of the time, it might crash at any point, or something worse might happen.

void* should be avoided in all but a few rare cases in C++; instead of resorting to using void*, you should consider using class inheritance, polymorphism, or templates to be sure that your code is type safe. While C++ does allow you to write code that is not type safe, it also provides many tools that help you to write type safe code and make that code much more straightforward, simple, and correct.


No. If you could not cast a void*. what could you do with it!? In fact you must cast it in order to assign it to a pointer of some other type or dereference it.

In your example you used a C style cast, C++ supports several safer cast operators such as dynamic_cast which does test the validity of the cast at run-time.


No, it isn't. That's why using void* in C++ is bad practice.

Use templates instead of void*. they are type safe.

void* should be used only when you are dealing with C code.


No. either in C or in C++ this is a basic operation we can do in this language.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜