【发布时间】:2021-10-20 20:38:50
【问题描述】:
我在这里有一个单例类声明:
#ifndef GLFW_CONTEXT_H
#define GLFW_CONTEXT_H
#include <memory>
class GLFWContextSingleton
{
public:
static std::shared_ptr<GLFWContextSingleton> GetInstance();
~GLFWContextSingleton();
GLFWContextSingleton(const GLFWContextSingleton& other) = delete;
GLFWContextSingleton* operator=(const GLFWContextSingleton* other) = delete;
private:
GLFWContextSingleton();
};
#endif
以及此处显示的GetInstance 函数的实现
std::shared_ptr<GLFWContextSingleton> GLFWContextSingleton::GetInstance()
{
static std::weak_ptr<GLFWContextSingleton> weak_singleton_instance;
auto singleton_instance = weak_singleton_instance.lock();
if (singleton_instance == nullptr)
{
singleton_instance = std::make_shared<GLFWContextSingleton>();
weak_singleton_instance = singleton_instance;
}
return singleton_instance;
}
但是对std::make_shared<GLFWContextSingleton>() 的调用给了我一个错误提示
‘GLFWContextSingleton::GLFWContextSingleton()’ is private within this context
我认为这个静态方法可以访问私有成员函数。这是什么原因造成的,我该如何解决?
【问题讨论】:
-
函数
std::make_shared<GLFWContextSingleton>()不是您班级的friend。它不能使用private构造函数。 -
是的,
static函数具有访问权限。你可以做singleton_instance.reset(new GLFWContextSingleton);- 这是你调用的函数make_shared,它没有访问权限。 -
你有什么理由想要一个
shared_ptr给单身人士顺便说一句? Mayers 类型的单身人士不会工作吗? -
@TedLyngmo 我认为使用
shared_ptr可能会更好,因为我可以使用weak_ptr来测试对象是否已初始化。但既然你提到了它,我认为不需要它,并且可能只返回对裸静态对象本身的引用。 -
更不用说,
GetInstance()的显示方式,如果多个线程同时调用GetInstance(),就会出现竞争条件。返回一个静态对象可以避免这种情况。