I am implementing a singleton class as an exercise in c++14 where use of smart pointer is mandatory. This code snippet works but I wanted to use make_unique , not to confuse with the old new and delete keywords, but it says it cannot access private member. Why is it happening? Is keyword 'new' safe for use with smart pointers?
#include <iostream>
#include <memory>
using namespace std;
class foo
{
private:
int val_;
private:
foo() {}
public:
// properties
void set(const int v) { val_ = v; }
int get() const { return val_; }
//methods
static const unique_ptr<foo>& get_instance()
{
static unique_ptr<foo> pfoo( new foo() );
//unique_ptr<foo> pfoo = make_unique<foo>() ; // Error - cannot access private member declared in class 'foo'
return pfoo;
}
};
int main()
{
foo::get_instance()->set(100);
cout << foo::get_instance()->get() <<endl;
}
Edited: get_instance() declared as const to disallow reset from caller.