【问题标题】:Can I use smart pointer with a mutex member?我可以将智能指针与互斥锁成员一起使用吗?
【发布时间】:2021-03-09 21:52:06
【问题描述】:

假设我有一个动态分配的对象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;
      |     ^~~~~

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

【问题讨论】:

    标签: c++ c++11 unique-ptr


    【解决方案1】:

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

    要获得一个管理默认构造的foostd::unique_ptr,您可以省略临时对象:

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

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 2013-03-30
      • 2018-07-18
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2021-08-19
      相关资源
      最近更新 更多