我在努力正确初始化的std::unique_ptr
's。矢量<unique_ptr>的初始化失败,出现复制错误
示例代码:
#include <iostream>
#include <vector>
#include <memory>
class Base{
public:
std::string getString() { return this->string; };
protected:
std::string string;
};
class Derived: public Base{
public:
Derived(std::string bla){
this->string = bla;
}
};
class Collection{
protected:
std::vector<std::unique_ptr<Base>> mappings;
};
class DerivedCollection: public Collection{
public:
DerivedCollection(std::string bla){
std::vector<std::unique_ptr<Base>> maps;
maps.push_back(std::make_unique<Derived>(bla));
//or this: (does not work aswell)
//maps.emplace_back(new Derived(bla));
this->mappings = maps;
}
};
int main(int argc, char** argv){
DerivedCollection test = DerivedCollection("bla");
return 0;
}
不知何故只定义mappings
触发错误:
/usr/include/c++/6.3.1/bits/stl_construct.h:75:7:
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Base; _Dp = std::default_delete<Base>]’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
告诉我,我莫名其妙地设法从一个const的unique_ptr,这是自不起作用构造的unique_ptr unique_ptr不是可复制构建的。
不知何故,即使我对DerivedCollection
构造函数中的所有内容进行评论,仍然会失败。
我的猜测是我需要一个适当的构造函数为Collection
类。我不知道如何定义它。
任何想法?
- 马尔特
或者,'std:swap(映射,映射)' – WhozCraig
哇,这很简单。关于其他问题:这只是我在大约30秒内放在一起的一个简单例子,因此可以解释马虎的风格。此外,这个问题出现在我需要非平凡构造函数逻辑的上下文中,这就是为什么我没有使用启动列表。感谢您的提示,但! – Malte