lundi 13 septembre 2021

How to pass static method of the class as deleter for std::unique_ptr?

I have been trying to pass a static method of following class as deleter of unique_ptr but I couldn't figure out the correct syntax. Please excuse if the below syntax is horribly wrong as I just started hands on with unique_ptr.

#include <iostream>
#include <memory>


class Singleton {

public:

    static void deleter(Singleton* p) {
        delete p;
        std::cout << "In deleter\n" << std::endl;
    }

    static std::unique_ptr<Singleton, decltype(&Singleton::deleter)>& getInstance(void);

    void hello (void) {
       std::cout << "Hello!\n" << std::endl;
    }

    Singleton(const Singleton&) = delete;
    Singleton(Singleton&&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    Singleton& operator=(Singleton&&) = delete;

private:
    static std::unique_ptr<Singleton, decltype(&Singleton::deleter)> s_instance_;

    Singleton() { std::cout << "Constructed\n" << std::endl; }

    ~Singleton() { std::cout << "Destroyed\n" << std::endl; }

};

std::unique_ptr<Singleton, decltype(&Singleton::deleter)>&
Singleton::getInstance (void)
{
    if (s_instance_ == nullptr) {
        s_instance_ = std::unique_ptr<Singleton, decltype(&Singleton::deleter)>(new Singleton(), &Singleton::deleter);
    }

    return s_instance_;
}

std::unique_ptr<Singleton, decltype(&Singleton::deleter)> Singleton::s_instance_{nullptr};

int main ()
{
    bool some_condition = true;
    std::unique_ptr<Singleton, decltype(&Singleton::deleter)> &ins = Singleton::getInstance();

    ins->hello();

    if (some_condition) {
       ins.reset();
    }

    std::cout << "End of main\n" << std::endl;
    return 0;
}

This gives following error with g++ (--version == g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609)

In file included from /usr/include/c++/5/memory:81:0,
                 from uptr.cpp:2:
/usr/include/c++/5/bits/unique_ptr.h: In instantiation of ‘constexpr std::unique_ptr<_Tp, _Dp>::unique_ptr() [with _Tp = Singleton; _Dp = void (*)(Singleton*)]’:
/usr/include/c++/5/bits/unique_ptr.h:200:61:   required from ‘constexpr std::unique_ptr<_Tp, _Dp>::unique_ptr(std::nullptr_t) [with _Tp = Singleton; _Dp = void (*)(Singleton*); std::nullptr_t = std::nullptr_t]’
uptr.cpp:44:89:   required from here
/usr/include/c++/5/bits/unique_ptr.h:159:9: error: static assertion failed: constructed with null function pointer deleter
       { static_assert(!is_pointer<deleter_type>::value,
         ^

Also, is there a way I can shorten std::unique_ptr<Singleton, decltype(&Singleton::deleter)> ? I tried using following approach before class definition but the compiler errors out for incomplete type:

using SingletonUPtr = std::unique_ptr<Singleton, decltype(&Singleton::deleter)>;

Aucun commentaire:

Enregistrer un commentaire