在基构造函数中初始化唯一指针的标准容器
Initialize standard container of unique pointers in base constructor
如果在编译时容器及其内容是已知的,那么在基构造函数中初始化具有唯一指针的标准库容器的首选方法是什么?c++不允许初始化列表与唯一指针一起使用,因为它们强制执行复制操作,所以我目前使用了一个丑陋的lambda解决方案:
#include <memory>
#include <vector>
#include <string>
using namespace std; // Note: for readability only
// Some non-POD object
class Object {
public:
Object(const string& desc) : description(desc) { }
string description;
void func () { /* do stuff */ }
};
// This class stores a vector of unique pointers to objects
class BaseX {
public:
const vector< unique_ptr<const Object> > objects;
BaseX (vector< unique_ptr<Object> > vec) :
objects { make_move_iterator(vec.begin()), make_move_iterator(vec.end()) } { }
};
// This class is a special case of BaseX where the object definitions are constant, and known at compile time (static).
// Question is how to initialize them...
class DerivedX : public BaseX {
public:
DerivedX () : BaseX(
// Using a lambda function is a messy idea, but works
[]()->vector< unique_ptr<Object> > {
unique_ptr<Object> objects[] = {
make_unique<Object>("My object")
};
return { make_move_iterator(begin(objects)), make_move_iterator(end(objects)) };
}()
) { }
};
这似乎是一个应该使用static
的情况,但不确定它适合在哪里…
我可能会这样做:
class DerivedX : public BaseX {
public:
DerivedX () : BaseX(make_vec()) { }
private:
static auto make_vec()
{
std::vector<std::unique_ptr<const O>> v(2);
v[0] = std::make_unique<O>("1");
v[1] = std::make_unique<O>("2");
return v;
}
};
(使用auto
返回类型,因为您似乎正在使用c++ 14,如果您有make_unique
,如果您使用c++ 11,那么只需显式拼写返回类型。)
相关文章:
- 如何将元素插入到标准::地图的共享指针中?
- 我想获取点的属性,它报告错误 C3867:"point::output_x":非标准语法;使用"&"创建指向成员的指针
- 非标准语法,使用 & 创建指向成员的指针
- 非标准语法使用 '&' 创建指向成员 C++ 的指针
- 如何在C++代码中灵活使用和替换标准::shared_ptr或标准::unique_ptr或原始指针?
- 是否可以在标准弱指针之上实现非拥有"slightly smart"指针?
- 是否可以从标准输入指向指针的地址
- 您将如何使用标准引号解释指向基类和派生类成员的指针的这种差异?
- 'cv::Mat::type':非标准语法;使用 '&' 创建指向成员的指针
- registerPointPickingCallback (PCLViewer::callback_Test,(void*)&viewer);返回 C3687 非标准语法;使用"&"创建指向成员的指针
- C++ Visual Studio 2015:非标准语法;使用 '&' 创建指向成员的指针
- C 11中的标准方法是什么,可以访问std :: vector中元素n的指针
- 使用多个参数将成员功能指针转换为标准C函数
- 非标准语法;使用 & 创建指向成员的指针
- Visual Studio 2015"非标准语法;使用"&"为成员创建指针"
- 在标准布局对象中进行指针运算(例如,使用偏移量)时,我们是否需要使用 std::launder?
- 为什么std::unique_ptr比标准指针慢得多..在优化之前
- 将标准::指针列表转换为标准::值列表的快速方法
- 为什么c++共享指针的行为不像迭代器的标准指针
- C++中返回局部变量的引用和标准指针的替代方案是什么