简体   繁体   English

删除在C ++中从void转换的指针是否安全?

[英]Is it safe to delete a pointer that was cast from void in C++?

Say I've got something like that in a public header: 说我在公共标题中有这样的东西:

class MyClass
{
public:
    MyClass();

protected:
    virtual ~MyClass();

private:
    void *pSomeInternalClass;
}

And here's my implementation: 这是我的实施:

MyClass::MyClass()
{
    pSomeInteralClass = (void *) new SomeInternalClass();
}

MyClass::~MyClass()
{
    SomeInternalClass *pTemp = (SomeInternalClass *) pSomeInternalClass;
    delete pTemp;
    pSomeInternalClass = NULL;
}

The idea behind the void pointer is that I dont't have to include the definitions for the internal class in the public headers. void指针背后的想法是我不必在公共头文件中包含内部类的定义。

My question is: am I handling the void pointer in a safe way? 我的问题是:我是否以安全的方式处理空指针? Is there any problem with its deletion? 删除有什么问题吗?

Thanks! 谢谢!

It's safe as long as you cast it back to it's original type. 只要你把它重新投入原始类型,它就是安全的。

But you don't need to do that. 但你不需要这样做。 Just forward-declare your internal type in your public header, and you don't need to do this nasty cast. 只需在公共标题中向前声明你的内部类型,你就不需要做这个讨厌的演员。

class YourClass {
  ...
  private:
    class Internal;
    Internal *pInternal;
};

You do not need to include the definitions for the class in the public headers. 您不需要在公共标头中包含该类的定义。 ie

class SomeInternalClass ;
class MyClass 
{ 
public: 
    MyClass(); 

protected: 
    virtual ~MyClass(); 

private: 
    SomeInternalClass *pSomeInternalClass; 
}

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

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