简体   繁体   中英

C2248 error when using smart pointers in singleton class

In below code I'm having C2248 error. 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?

    #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; however, that constructor is implicitly declared as private (which is the default access specifier for class members).

To fix this issue, just add the public: access specifier before your constructor definition:

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). Thus, your getInstance function would then be:

    static std::shared_ptr<GameSetting> getInstance()
    {
        if (!_instance)
            _instance = std::shared_ptr<GameSetting>{new GameSetting};
        return _instance;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM