我可以将智能指针与互斥成员一起使用吗?
Can I use smart pointer with a mutex member?
假设我有一个动态分配的对象 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>();
假设我有一个动态分配的对象 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>();