2 years ago

#53732

test-img

Harry

How to create a singleton object using std::unique_ptr of a class with private destructor?

How to create a singleton class using std::unique_ptr? My current implementation makes use of a static function get_instance() for initializing the std::unique_ptr. I'm using std::once_flag and std::call_once for thread safety inside get_instance().

The problem I'm facing is I want to make the destructor private, but I'm getting a compiler error since std::unique_ptr can't access the private destructor.

This is my sample code:

#include <iostream>
#include <memory>
#include <mutex>
#include <functional>

class A final {
    A() {
        std::cout << "constructor" << std::endl;
    }

    ~A() {
        std::cout << "Destructor" << std::endl;
    }

    inline static std::unique_ptr<A> instance;
    inline static std::once_flag instance_flag;
    inline static std::once_flag destruct_flag;

public:
    static std::unique_ptr<A>& get_instance() {
        std::call_once(instance_flag, [] () {
            instance.reset(new A()); 
        });

        return instance;
    }

    static void release_instance() {
        std::call_once(destruct_flag, [] () {
            instance.release();
        });
    }
};

int main() {
    A::get_instance();
    A::release_instance();
}

c++

singleton

0 Answers

Your Answer

Accepted video resources