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

时间:2013-01-02 06:08:05

标签: c++

我想在编译时生成一组多态类型。在运行时指定对数组的访问(否则我将使用元组)。我希望数组通过unique_ptr拥有它的元素。目前我正在使用可变参数模板来创建数组。我正在尝试做的简化版本(MSVC 2012 November 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数组。我仍然试图围绕可变参数模板。

2 个答案:

答案 0 :(得分:0)

RHS是否需要使用unique_ptr进行初始化?不能使用unique_ptr的构造函数吗?你试过吗

std::array<unique_ptr<foo>, tuple_size<t>::value> l = { new args()... }; 

答案 1 :(得分:0)

您想要做的事情基本上有效:

std::array<unique_ptr<foo>, tuple_size<t>::value> l = { unique_ptr<args>(new args())... };

将编译(甚至在MSVC上!),因为你正在构建temporaries并且将调用move构造函数(如果不是,则添加std::move将修复它)。

您接下来要做的事情不是:

return l;

因为你试图按值返回不可复制的unique_ptrs数组。

相关问题