使用共享指针实现单例的正确方法? 我尝试了我的第一个更大的C++对象,当使用共享指针实现单体时,我遇到了一个问题。
当我尝试编译以下内容时,Visual Studio会出现以下错误: 错误C2248“PaletteManager::PaletteManager”:无法访问私有 在类“PaletteManager”{省略}\xmemory行228中声明的成员 我猜问题是因为我有一个私有构造函数/析构函数,make_shared正在尝试调用构造函数。这个访问问题对我来说很有意义,但是如果我想使用共享指针作为访问我的单例对象的方式,我应该怎么做?这段代码在使用原始指针时效果很好,但我想尝试使用智能指针以干净的方式进行操作 下面是有关代码的头文件:使用共享指针实现单例的正确方法? 我尝试了我的第一个更大的C++对象,当使用共享指针实现单体时,我遇到了一个问题。,c++,singleton,C++,Singleton,当我尝试编译以下内容时,Visual Studio会出现以下错误: 错误C2248“PaletteManager::PaletteManager”:无法访问私有 在类“PaletteManager”{省略}\xmemory行228中声明的成员 我猜问题是因为我有一个私有构造函数/析构函数,make_shared正在尝试调用构造函数。这个访问问题对我来说很有意义,但是如果我想使用共享指针作为访问我的单例对象的方式,我应该怎么做?这段代码在使用原始指针时效果很好,但我想尝试使用智能指针以干净的方式进
class PaletteManager
{
private:
// array representing palette colors
uint* paletteColors;
// private constructor/destructor because singleton
PaletteManager();
~PaletteManager();
// load palette from file TODO: not implemented
void loadPallette();
static std::shared_ptr<PaletteManager> instance;
public:
const uint PALETTE_MAX_COLORS = 4;
uint getPaletteColor(uint idx);
// singleton accessor
static std::shared_ptr<PaletteManager> getInstance();
};
类调色板管理器
{
私人:
//表示调色板颜色的数组
uint*浅色;
//私有构造函数/析构函数,因为singleton
PaletteManager();
~PaletteManager();
//从文件TODO加载调色板:未实现
无效加载托盘();
静态std::共享的ptr实例;
公众:
常数调色板的最大颜色=4;
uint getPaletteColor(uint idx);
//单重存取器
静态std::shared_ptr getInstance();
};
以下是cpp文件中讨论的函数:
std::shared_ptr<PaletteManager> PaletteManager::instance = nullptr;
std::shared_ptr<PaletteManager> PaletteManager::getInstance()
{
if (!PaletteManager::instance)
{
PaletteManager::instance = std::make_shared<PaletteManager>();
}
return PaletteManager::instance;
}
std::shared_ptr palettmanager::instance=nullptr;
std::shared_ptr PaletteManager::getInstance()
{
如果(!PaletteManager::实例)
{
PaletteManager::instance=std::make_shared();
}
返回PaletteManager::实例;
}
PaletteManager::instance=std::make_shared();
这导致std::make_shared
尝试new
aPalleteManager
对象,然后从中构造std::shared_ptr
。这就是std::make_shared
所做的,这就是它的工作原理
这在这里不起作用:因为
这个类的成员new
中的对象,它可以使用私有构造函数,然后从指向这个新对象的指针手动构造getInstance
std::shared_ptr
TLDR:不能对具有私有构造函数的对象使用
std::make_shared
。C++的规则不允许您这样做。您可以使用私有构造函数将std::make_unique()
作为类的友元函数。大概这也适用于std::make_shared()
?(但我还没有测试过。)
例如,请参见:
可能重复
PaletteManager::instance = std::make_shared<PaletteManager>();