我可以将智能指针与互斥锁成员一起使用吗?

假设我有一个动态分配的对象foo,它有一个std::mutex成员:

#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;
}

我尝试使用智能指针,但没有任何意义:

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;
      |     ^~~~~

我必须使用原始指针来管理这个对象吗?

回答

您正在构造一个临时对象foo()并将其传递给std::make_unique(). std::make_unique()将从临时 构造托管对象foo,但foo不可复制或移动。

std::unique_ptr管理默认构造的foo,您可以省略临时对象:

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


以上是我可以将智能指针与互斥锁成员一起使用吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>