hello
hello

Reputation: 1229

Singletons with constructor arguments

While trying do create a single instance of a class which will require global access and modification to it's name, I have some syntax related issue (I think) with my code in the implementation file.

When I compile, I get error on the return statement:

non-const lvalue reference to type Single cannot bind to a value of unrelated type Single.

single.h

class Single{
public:
   std::string getSingleName();
   void updateSingleName(std::string name);
   void operator=(Single const&) = delete;
   Single(Single const&) = delete;
   static Single& getInstance(const std::string& name);

private:
    Single(std::string singleName);  
    std::string name;
};

Single.cpp

Single& Single::getInstance(const std::string& name){
     Single single(std::string name);
     return single;
}

Upvotes: 2

Views: 2924

Answers (2)

NathanOliver
NathanOliver

Reputation: 180955

You forgot the static keyword for single in getInstance. In order to return a reference you need a persistent object. We do that with static like

Single& Single::getInstance(const std::string& name){
     static Single single(name); // get rid of the parameter type otherwise this is a function
     return single;
}

Do note that since single is now static it is only ever constructed once and any subsequent call to getInstance will return the same object as the previous call.

If you need to have multiple single objects that have different names then you are going to need something other than a singleton. Possibly just getting rid of the copy constructor and making it movable will work for your use case.

Upvotes: 2

gnasher729
gnasher729

Reputation: 52602

The combination of singleton and constructor arguments doesn't make any sense whatsoever. The point of a singleton is that (1) it exists at most once, and (2) anyone can get the singleton object at any time without having to check that someone has already created it - which means everyone would need to know the parameters, and obviously they would have to be the same, otherwise the singleton would behave differently depending on who created it.

Upvotes: 4

Related Questions