无法在unique_ptr中使用初始化列表的解决方法

Workaround for being unable to use initializer lists with unique_ptr?

本文关键字:初始化 列表 方法 解决 unique ptr      更新时间:2023-10-16

我想有一个在编译时生成的多态类型数组。对数组的访问是在运行时指定的(否则我就使用元组)。我想通过一个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数组