1

I came across this question and the accepted and most voted answer proposes the following

static shared_ptr<Foo> getInstance()
{
    static std::shared_ptr<Foo> instance = std::make_shared<Foo>();
    return instance; 
}

So I wrote this small piece of code

class Manager 
{  
  public:  
  static std::shared_ptr<Manager> get_instance()
  {
    //static std::shared_ptr<Manager> instance = std::make_shared<Manager>();
    static std::shared_ptr<Manager> instance(new Manager());
    return instance;
  } 
  private:  
  Manager() = default;
  Manager(Manager const&) = delete;
  void operator=(Manager const&) = delete;
};

int main ()
{
    std::shared_ptr<Manager> ptr = Manager::get_instance();
    return 0;
}

and to my surprise when I use std::make_shared compiler (g++ v5) complains that the singleton constructor is private (as it should be for singleton). The second way - using new operator directly - worker without problem.

Is this reasonable - should it work like that? I wouldn't be upset (maybe I am not a purist) if this line was a valid c++ code. Can someone provide me further explanation about that - especially because make_shared is usually more efficient, isn't it?

Community
  • 1
  • 1
Vivian Miranda
  • 2,276
  • 1
  • 13
  • 26
  • @JonathanPotter. Thanks for citing the other question. I haven't found that before writing me own. It was not clear there - and maybe this is something new - why the second version with operator new works. – Vivian Miranda Jan 19 '16 at 19:28
  • 1
    The second version works because `new Manager()` constructs the class inside the function which is okay. `make_shared` fails because it cannot call a private constructor. – NathanOliver Jan 19 '16 at 19:30
  • 1
    When you use `operator new` you're just passing the `shared_ptr` constructor a pointer to an already existing object, which all it has to do is store. It doesn't have any of the requirements that `make_shared` has. – Jonathan Potter Jan 19 '16 at 19:30
  • It is also very strange indeed to have a Singlton inside `shared_ptr`. It is certainly a way to raise a couple of brows. – SergeyA Jan 19 '16 at 19:32
  • @SergeyA. Yes - I agree. But I am not asking if it makes sense to have singleton inside shared_ptr. I was just trying to reproduce an accepted answer and I this issue raised. Using shared_ptr makes sense if you are trying to build phoenix singletons (see the question/answer I linked) – Vivian Miranda Jan 19 '16 at 19:34
  • Another reason to use that is the fact that some interfaces might require share_ptrs – Vivian Miranda Jan 19 '16 at 19:39

0 Answers0