5

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.

ark1974
  • 451
  • 3
  • 13
  • 1
    Is there any advantage in using a `unique_ptr` over using a static instance by value? Can't callers delete/replace your singleton by calling `reset()`? – Galik Feb 14 '18 at 06:00
  • Before anybody complains the duplicate list is about "make_shared", bear in mind that the same **relevant** considerations apply to both functions. For this type of question they differ only in name and return type. – StoryTeller - Unslander Monica Feb 14 '18 at 06:03
  • @Galik: static unique_ptr pfoo; if( pfoo == nullptr) pfoo.reset(new foo()); should also work. But still make_unique fails this way too. I search stackoverflow for answer so i put the question here. Not duplicate please. – ark1974 Feb 14 '18 at 06:05
  • 1
    If you want a singleton then I recommend this approach: https://stackoverflow.com/a/1008289/3807729 – Galik Feb 14 '18 at 06:07

0 Answers0