lundi 4 mai 2020

RAII with std::function

Is std::function smart in nature like std::shared_ptr and std::unique_ptr? I guess no? I have a std::function which is a class member like below.

class MyClass {
    typedef std::function<void(void)> Func;
    Func m_func;

public:
    MyClass() {
        m_func = []() {
            std::cout << "Func called" << std::endl;
        }
    }

    ~MyClass() {
       m_func = nullptr; // Is this required? 
    }
}

Question:
Is it mandatory to assign nullptr to m_func in the destructor? Or should I make m_func into a smart pointer by doing something like below? Or is it that m_func is smart by default and implicitly follows RAII?

class MyClass {
    typedef std::function<void(void)> Func;
    std::unique_ptr<Func> m_func;

public:
    MyClass() {
        m_func = std::make_unique<Func>();
        *m_func = []() {
            std::cout << "Func called" << std::endl;
        }
    }

    ~MyClass() {
       // auto released
    }
}

Aucun commentaire:

Enregistrer un commentaire