Closed. This question is off-topic 。它目前不接受答案。
想改善这个问题吗? Update the question 所以它是堆栈溢出的 on-topic。
8年前关闭。
Improve this question
以下代码是我对单例模式的实现。
它以这种形式工作,但是由于 Singleton 的构造函数和析构函数受到保护而不是私有(private),因此我不确定它是否真的正确。如果我将它们声明为私有(private),则代码将无法编译,因为类无法访问它们。这个实现是否可以安全使用,或者我可以做些什么来改进它以确保只会创建和使用一个实例。
谢谢 你的
我会重新实现你的访问器:
然后确保在应用程序的主线程中调用
想改善这个问题吗? Update the question 所以它是堆栈溢出的 on-topic。
8年前关闭。
Improve this question
以下代码是我对单例模式的实现。
#include <iostream>
template<class T>
class Uncopyable
{
protected:
Uncopyable(){}
~Uncopyable(){}
private:
Uncopyable(const Uncopyable<T>&);
Uncopyable& operator=(const Uncopyable<T>&);
};
template <class T>
class Singleton : private Uncopyable<T>
{
public:
static T* getInstancePtr()
{
return instance;
}
protected:
Singleton<T>()
{
if(instance == 0)
{
instance = new T();
}
};
~Singleton<T>()
{
};
private:
static T* instance;
};
template<class T> T* Singleton<T>::instance = 0;
class Test : public Singleton<Test>
{
public:
Test(){};
~Test(){};
inline void test() const
{
std::cout << "Blah" << std::endl;
}
private:
friend class Singleton<Test>;
protected:
};
int main(int argc, char* argv[])
{
Test* t = Test::getInstancePtr();
Test* t2 = Test::getInstancePtr();
t->test();
t2->test();
return 0;
}
它以这种形式工作,但是由于 Singleton 的构造函数和析构函数受到保护而不是私有(private),因此我不确定它是否真的正确。如果我将它们声明为私有(private),则代码将无法编译,因为类无法访问它们。这个实现是否可以安全使用,或者我可以做些什么来改进它以确保只会创建和使用一个实例。
谢谢
最佳答案
您发布的代码有几处错误。
Uncopyable
类不需要模板化 Singleton
类不是线程安全的 Singleton
实例永远不会被删除 我会重新实现你的访问器:
static T& GetInstance()
{
static T instance;
return instance;
}
然后确保在应用程序的主线程中调用
Singleton<T>::GetInstance()
(在初始化期间)以避免任何线程问题。关于c++ - 这是单例模式的正确实现吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13398313/