I have a singleton class declaration here:
#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
and an implementation of the GetInstance
function shown here
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;
}
However the call to std::make_shared<GLFWContextSingleton>()
gives me an error saying
‘GLFWContextSingleton::GLFWContextSingleton()’ is private within this context
I thought that this static method would have access to the private member functions. What is causing this and how do I fix it?
std::make_shared<GLFWContextSingleton>()
is not afriend
of your class. It can't use theprivate
constructor.static
function has access. You can dosingleton_instance.reset(new GLFWContextSingleton);
- it's the function you call,make_shared
, that doesn't have access.shared_ptr
to the singleton btw? Wouldn't a Mayers-kind-of-singleton work?shared_ptr
because I can use aweak_ptr
to test if the object has been initialized or not. But now that you mention it, I don't see a need for it and probably can just return a reference to a bare static object itself.GetInstance()
is shown, there is a race condition if multiple threads were to callGetInstance()
at the same time. Returning a static object would avoid that.