无法在unique_ptr中使用初始化列表的解决方法
Workaround for being unable to use initializer lists with unique_ptr?
我想有一个在编译时生成的多态类型数组。对数组的访问是在运行时指定的(否则我就使用元组)。我想通过一个unique_ptr数组拥有它的元素。目前,我正在使用可变模板来创建数组。我想做的事情的简化版本(MSVC 2012 11月CTP):
#include "stdafx.h"
#include <array>
#include <memory>
#include <tuple>
#include <initializer_list>
#include <iostream>
using namespace std;
class foo { };
class bar : public foo { };
class wiz : public foo { };
struct house
{
template<class... args>
struct furniture
{
typedef tuple<args...> t;
static std::array<unique_ptr<foo>, tuple_size<t>::value> make()
{
std::array<unique_ptr<foo>, tuple_size<t>::value> l = { unique_ptr<args>(new args())... };
return l;
}
};
typedef furniture<bar, wiz> td;
};
int _tmain(int argc, _TCHAR* argv[])
{
auto result = house::td::make();
return 0;
}
不幸的是,我看到了编译器错误:
error C2248: 'std::unique_ptr<foo,std::default_delete<_Ty>>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<foo,std::default_delete<_Ty>>'
这是因为初始化列表通过拷贝工作,但unique_ptr是不可复制的。我可以通过使用shared_ptr(或原始指针)来解决这个问题,它提供了我想要的行为,但我很好奇是否有一种方法可以创建这样的unique_ptr数组。
RHS需要用unique_ptr
s初始化吗?不能使用unique_ptr
的构造函数吗?你有没有试过
std::array<unique_ptr<foo>, tuple_size<t>::value> l = { new args()... };
你想做的基本上是有效的:
std::array<unique_ptr<foo>, tuple_size<t>::value> l = { unique_ptr<args>(new args())... };
将编译(即使在MSVC上!),因为你从临时构造和移动构造函数将被调用(如果它不是,添加std::move
将修复它)。
你接下来要做的事情没有:
return l;
因为您试图按值返回不可复制的unique_ptrs数组
相关文章:
- C++类 - 初始化列表 - 递归 - 按值传递
- 在初始化列表之外手动调用基类的构造函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- std::map与谓词与初始化列表
- 类内初始化与构造函数初始化列表的顺序
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++初始化列表与分配值
- C++初始化列表中的向量集大小或调整大小
- 在构造函数初始化列表中使用 std::variant
- emplace_back初始化列表错误,当初始化列表在独立变量上工作时
- 解释了构造函数成员初始化列表
- 使用初始化列表时如何获取私有数据?
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 如何在成员初始化列表中声明共享指针
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 我可以检查初始化列表中设置的构造函数主体中的变量吗
- 使用整数初始化列表初始化长双精度的向量
- 是否可以在C++中使用初始化列表设置数组的特定成员?