pro*_*eek 3 c++ smart-pointers map variable-assignment
我正在尝试使用一种方法设置一个unique_ptr的映射。
class A {
map<int, unique_ptr<B>> x;
public:
void setx(const map<int, unique_ptr<B>>& x) {this->x = x;} // <-- error
...
};
Run Code Online (Sandbox Code Playgroud)
但是,我得到了这个错误。
'constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = std::unique_ptr<ContextSummary>]' is implicitly deleted because the default definition would be ill-formed:
Run Code Online (Sandbox Code Playgroud)
这项作业有什么问题?
std::unique_ptr
是不可复制的,因此您不能复制std::map
持有的unique_ptrs
。您可以移动它:
void setx(map<int, unique_ptr<B>> x) {
this->x = std::move(x);
}
Run Code Online (Sandbox Code Playgroud)
请注意,要移动地图,您不需要将其作为const
参考,否则就无法移动。按值取值允许调用者使用临时值或移动的左值。
所以现在,您将使用如下代码:
std::map<int, std::unique_ptr<B>> some_map = ...;
some_a.setx(std::move(some_map));
Run Code Online (Sandbox Code Playgroud)
或像这样,使用临时对象:
some_a.setx({
{1, make_unique<B>(...)},
{2, make_unique<B>(...)}
});
Run Code Online (Sandbox Code Playgroud)
如0x499602D2所指出的,您可以直接在构造函数中执行此操作:
A::A(map<int, unique_ptr<B>> x)
: x(std::move(x)) {
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2440 次 |
最近记录: |