我在這里有一個單例類宣告:
#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
我認為這個靜態方法可以訪問私有成員函式。這是什么原因造成的,我該如何解決?
uj5u.com熱心網友回復:
靜態函式確實可以訪問私有成員。make_shared才不是。
make_shared是一個模板函式,它轉發它獲取的引數并呼叫指定類的建構式。所以對默認構造make_shared函式的呼叫發生在函式內部,而不是在GetInstance函式內部,因此出現錯誤。
解決這個問題的一種方法是使用私有嵌套類作為建構式的唯一引數。
#include <memory>
class GLFWContextSingleton
{
private:
struct PrivateTag {};
public:
static std::shared_ptr<GLFWContextSingleton> GetInstance();
~GLFWContextSingleton();
GLFWContextSingleton(const GLFWContextSingleton& other) = delete;
GLFWContextSingleton* operator=(const GLFWContextSingleton* other) = delete;
GLFWContextSingleton(PrivateTag);
};
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>(PrivateTag{});
weak_singleton_instance = singleton_instance;
}
return singleton_instance;
}
int main() {
}
通過這種方式,我們將建構式保持為公開狀態,但為了使用它,我們需要一個PrivateTag只能被類成員訪問的 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/328467.html
上一篇:如果一個函式定義有一個類模板型別的引數并且沒有使用它(它的成員),那么它是否被實體化?
下一篇:什么時候實體化模板?
