你能删除本地静态变量吗?

BK *_* C. -1 c++ singleton static

我有我的单例类,它返回指向实例的本地静态的指针以确保线程安全.现在,如果我没有将析构函数声明为私有,用户可以将其删除吗?

对于前者

class Singleton
{
    Singleton();
    public:
    static Singleton *getInstance();

};

Singleton *Singleton::getInstance()
{
    static Singleton inst;
    return &inst;
}

// in user code
void foo()
{
    Singleton *inst = Singleton::getInstance();
    // do its stuff

    //accidentally delete instance here?! 
    // Should I have private destructor?
    delete inst;
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 5

在尝试删除指针的情况下foo如果使析构函数为私有,则会导致编译错误,因为析构函数不可访问.如果delete在当时的成员或朋友中调用Singleton它仍然会编译.那说尝试delete一个未分配的指针new是未定义的行为,所以我们应该尝试将它设置为用户甚至不小心尝试和调用的地方delete.

你可以阻止这种方法的一种方法是返回一个引用而不是一个指针.这样你的用户甚至不会尝试调用,delete因为他们正在处理非指针类型.

class Singleton
{
    Singleton() {};
    public:
    static Singleton& getInstance();
};

Singleton& Singleton::getInstance()
{
    static Singleton inst;
    return inst;
}
Run Code Online (Sandbox Code Playgroud)