【问题标题】:How do I initialize a class member `std::vector` of `std::unique_ptr` object in the constructor initializer list?如何在构造函数初始化列表中初始化 `std::unique_ptr` 对象的类成员 `std::vector`?
【发布时间】:2016-05-03 01:21:05
【问题描述】:

我的代码如下所示。

#include <memory>
#include <stdint.h>

class APodClass
{
    public:
        int x, y, z;
};

class MyClass
{
    public:
        MyClass(uintmax_t Width, uintmax_t Height)
            :   WIDTH   (Width),
                HEIGTH  (Height),
                Field   (WIDTH * HEIGTH, nullptr)
        {
        }

    private:
        const uintmax_t WIDTH;
        const uintmax_t HEIGTH;
        std::vector<std::unique_ptr<APodClass>> Field;
};

int wmain(int argc, wchar_t * argv[])
{
    MyClass MyObject(1000, 500);

    return 0;
}

当我尝试编译它时,我收到以下错误。

Error C2280
'std::unique_ptr<APodClass,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
...\visual studio\vc\include\xmemory0   655

我在这里做错了什么。如何修复此代码?

【问题讨论】:

    标签: c++ initialization containers unique-ptr


    【解决方案1】:

    std::unique_ptr 不可复制,因此任何复制元素的构造函数或算法(例如std::generate)都不起作用:

    class MyClass
    {
        static std::vector<std::unique_ptr<APodClass>> generate(size_t sz)
        {
            std::vector<std::unique_ptr<APodClass>> result;
            result.reserve(sz);
            for (size_t i = 0 ; i < sz ; ++i)
                result.emplace_back(nullptr);
    
            return result;
        }
    
    public:
        MyClass(uintmax_t Width, uintmax_t Height)
        :   WIDTH   (Width),
        HEIGTH  (Height),
        Field   (generate(WIDTH * HEIGTH))
        {
        }
    ...
    };
    

    【讨论】:

      【解决方案2】:

      如您所见,您使用的构造函数 vector(size_type n, const value_type&amp; val = value_type(), const allocator_type&amp; alloc = allocator_type()); 复制了 val 参数。

      如您所知,unique_ptr 不可复制。因此,您不能使用复制参数的构造函数。

      您可以做的是将向量初始化为空。默认初始化就足够了,所以完全不需要使用成员初始化列表。要将n 不可复制元素添加到空向量中,可以在MyClass 的构造函数主体内使用循环和push_back

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-14
        • 1970-01-01
        • 2015-05-22
        • 2017-04-04
        • 2020-09-03
        • 2020-05-05
        • 2016-05-07
        • 2015-08-05
        相关资源
        最近更新 更多