jeudi 26 novembre 2020

Can I use smart pointer with a mutex member?

Say I have a dynamic allocated object foo which have a std::mutex member:

#include <mutex>
#include <memory>

class foo {
    public:
        foo()=default;
        ~foo();
    private:
        std::mutex lock;
};

int main(){
    std::unique_ptr<foo> a = std::make_unique<foo>(foo());
    return 0;
}

I've tried to use a smart pointer, but it make no sense:

rog.cc:4:7: error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
In file included from /opt/wandbox/gcc-head/include/c++/11.0.0/mutex:43,
                 from prog.cc:1:
/opt/wandbox/gcc-head/include/c++/11.0.0/bits/std_mutex.h:94:5: note: declared here
   94 |     mutex(const mutex&) = delete;
      |     ^~~~~

shall I must use raw pointer to manage this object?

Aucun commentaire:

Enregistrer un commentaire