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?