Can I use smart pointer with a mutex member?

Viewed 242

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?

1 Answers

You're constructing a temporary object by foo() and passing it to std::make_unique(). std::make_unique() will construct the managed object from the temporary foo, but foo is not copyable nor moveable.

To get a std::unique_ptr managing a default-constructed foo, you can just omit the temporary object:

std::unique_ptr<foo> a = std::make_unique<foo>();
Related