0
我想在C++中创建一个简单的Singleton类,其中包含指向其他类型的指针。从单例类中删除对象
单身人士将在某个时刻成为该指针的所有者。
所以这是一个很好的方法来删除Test类型的对象并释放它在Singleton析构函数上的内存?
class Test{...};
class Singleton
{
public:
static Singleton& getInstance()
{
static std::unique_ptr<Singleton> instance(new Singleton());
return *instance.get();
}
void SetTest(Test* test);
Test* GetTest() const;
...
private:
Singleton(){}
~Singleton(){ if(test) delete test;} // ??
Test* test;
...
};
PS:我不能使用智能指针作为Test对象。
我猜你的意思是“指向其他类型的对象”,据我所知是没有指针类型 – user463035818
你或许应该初始化'在构造函数中test'。否则,如果用户从不调用SetTest,那么GetTest将返回一个无效的指针,并且析构函数会尝试删除未分配的东西。 –
严格来说,单身是反模式。而任何你需要它拥有的东西都可能代表你的代码中有更多的反模式。 – StoryTeller