构造unordered_map总是复制unique_ptr

时间:2020-03-14 20:58:28

标签: c++ c++17

由于某种原因,当试图构造一个无序映射(特别是一对)时,该映射试图复制对中的unique_ptr而不是移动它。我在做什么错了?

这是一个示例(已更新):

#include <unordered_map>
#include <memory>

class pointed
{
    bool x;
    int y;
public:
    float key;
    pointed( float key, bool x, int y ): x(x), y(y)
    { }
};

class test
{
    std::unordered_map< float, std::unique_ptr< pointed > > my_map;
public:
    template< typename... pointed_construction_t >
    test( pointed_construction_t &&... pointed_parameter_pack ):
        my_map
        {
            std::move
            (
                std::make_pair
                ( 
                    pointed_parameter_pack.key,
                    std::move
                    (
                        std::make_unique< pointed >
                        (
                            std::forward< pointed_construction_t >
                            ( 
                                pointed_parameter_pack 
                            )
                        ) 
                    )
                )
            )...
        }
    { }
};

int main( )
{
    float key = 2.f, key2 = 4.f;
    bool x = true, x2 = false;
    int y = 0, y2 = -1;
    test t( pointed( key, x, y ), pointed( key2, x2, y2 ), pointed( 6.f, false, 500 ) );
}

错误:使用已删除的功能

注意:在这里声明

406 | unique_ptr(const unique_ptr&)= delete;

1 个答案:

答案 0 :(得分:1)

使用my_map{...}进行列表初始化,并且编译器找到std::initializer_list的{​​{1}}构造函数。这将构造一个初始化列表,其中包含std::unordered_map个元素的数组。因此您的元素无法从列表移动到地图。

您必须进入构造函数,并放置该对中的元素:

const

有了您的新更新,我就能理解您想要什么。使用折叠表达式,以便为每个test(int key, pointed_construction_t&&... pointed_parameter_pack) { map.emplace(key, std::make_unique<pointed>(std::forward<pointed_construction_t>( pointed_parameter_pack)...)); } 参数调用emplace

pointed
相关问题