简体   繁体   English

C ++-转换void指针

[英]C++ - Casting void pointer

Does C++ throw runtime exceptions when you try to cast a void* to something that it isn't? 当您尝试将void*强制转换为不是的东西时,C ++是否会抛出运行时异常?

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? 当您尝试将void*强制转换为不是的东西时,C ++是否会抛出运行时异常?

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++; 在C ++中,除了少数几种罕见情况外,应避免使用void* instead of resorting to using void* , you should consider using class inheritance, polymorphism, or templates to be sure that your code is type safe. 而不是使用void* ,您应该考虑使用类继承,多态或模板来确保您的代码是类型安全的。 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. 尽管C ++允许您编写不是类型安全的代码,但它还提供了许多工具来帮助您编写类型安全的代码,并使该代码更加直接,简单和正确。

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. 在您的示例中,您使用了C样式强制转换,C ++支持一些更安全的强制转换运算符,例如dynamic_cast在运行时测试dynamic_cast的有效性。

No, it isn't. 不,不是。 That's why using void* in C++ is bad practice. 这就是为什么在C ++中使用void*是不好的做法。

Use templates instead of void* . 使用模板而不是void* they are type safe. 它们是类型安全的。

void* should be used only when you are dealing with C code. void*仅应在处理C代码时使用。

不,在C或C ++中,这是我们可以用这种语言进行的基本操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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