[英]C2248 error when using smart pointers in singleton class
In below code I'm having C2248 error.在下面的代码中,我遇到了 C2248 错误。 When I replace smart pointers with the raw pointers it compiles.
当我用它编译的原始指针替换智能指针时。 However I want to use smart pointer std::shared_ptr<> object. How can I correct this error when using smart pointer?
但是我想使用智能指针 std::shared_ptr<> object。使用智能指针时如何更正此错误?
#include <iostream>
#include <string>
#include <memory>
class GameSetting{
inline static std::shared_ptr<GameSetting> _instance;
unsigned int _brightness;
unsigned int _width;
unsigned int _heigth;
GameSetting():_brightness{150}, _width{300}, _heigth{200}
{}
public:
static std::shared_ptr<GameSetting> getInstance(){
if(! _instance)
_instance=std::make_shared<GameSetting>();
return _instance;
}
void setBrightness(unsigned brightness){_brightness=brightness;}
void setWidth(unsigned int width){_width=width;}
void setHeight(unsigned int height){_heigth=height;}
unsigned int getBrightness()const{return _brightness;}
unsigned int getWidth()const{return _width;}
unsigned int getHeigth()const{return _heigth;}
void displaySettings()const{
std::cout<<"brigthness: "<<_brightness<<'\n'<<"width: "<<_width
<<'\n'<<"heigth: "<<_heigth<<"\n\n";
}
};
int main()
{
std::shared_ptr<GameSetting> setting=GameSetting::getInstance();
setting->displaySettings();
}
The make_shared<GameSetting>()
call requires access to the default constructor of your GameSetting
class; make_shared<GameSetting>()
调用需要访问GameSetting
class 的默认构造函数; however, that constructor is implicitly declared as private
(which is the default access specifier for class members).但是,该构造函数被隐式声明为
private
(这是 class 成员的默认访问说明符)。
To fix this issue, just add the public:
access specifier before your constructor definition:要解决此问题,只需在构造函数定义之前添加
public:
访问说明符:
class GameSetting {
inline static std::shared_ptr<GameSetting> _instance;
unsigned int _brightness;
unsigned int _width;
unsigned int _heigth;
public: // Anything before this is "private" by default
GameSetting() :_brightness{ 150 }, _width{ 300 }, _heigth{ 200 }
{}
public:
static std::shared_ptr<GameSetting> getInstance()
{
if (!_instance)
_instance = std::make_shared<GameSetting>();
return _instance;
}
// ... the rest of you class definition
Alternatively, if you wish/need to keep your GameSetting
constructor private (as is common with singleton classes), then you can replace the call to std::make_shared
with a direct 'call' to the std::shared_ptr
constructor (and an assignment of the result).或者,如果您希望/需要将您的
GameSetting
构造函数保持私有(这在 singleton 类中很常见),那么您可以将对std::make_shared
的调用替换为对std::shared_ptr
构造函数的直接“调用”(以及一个赋值)结果)。 Thus, your getInstance
function would then be:因此,您的
getInstance
function 将是:
static std::shared_ptr<GameSetting> getInstance()
{
if (!_instance)
_instance = std::shared_ptr<GameSetting>{new GameSetting};
return _instance;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.