存储在std :: map里面的C std :: unique_ptr使用了被删除的函数ill形成的

我有以下代码,不会编译,它是星期五,我有点疲惫.
#include <string>
#include <memory>
#include <utility>
#include <map>

template< typename T,typename ...Args >
std::unique_ptr< T > make_unique( Args && ...args )
{
    return std::unique_ptr< T >( new T( std::forward< Args >( args )... ) );
}

struct A
{
};

std::map< std::string,std::unique_ptr< A > > _map = { { "A",make_unique< A >() } }; // <-- ERROR!!

以下编译没有问题

int main()
{
    std::pair< std::string,std::unique_ptr< A > > p { "B",make_unique< A >() };
    _map.insert( std::make_pair( "C",make_unique< A >() ) );
}

我得到的错误是(粗略地,删除了g)

use of deleted function 'constexpr std::pair<...>( const st::pair<...> & )
'constexp std::pair<...>::pair( const std::pair<...> & ) is implicitly deleted because the default deFinition would be illegal.

Argghh!
请阅读c 11标准中的内容.

When an aggregate is initialized by an initializer list,as specified
in 8.5.4,the elements of the initializer list are taken as
initializers for the members of the aggregate,in increasing subscript
or member order. Each member is copy-initialized from the
corresponding initializer-clause

无赖!

任何人都知道初始化列表是否完全不可能?

解决方法

您无法做很多事情:复制初始化列表中的元素.这与仅移动的类不相容.

有一种方法可以绕过这个“缺陷”,但阅读并不是很好;你决定

using map_type  = std::map< std::string,std::unique_ptr< A > >;
using pair_type = map_type::value_type;
pair_type elements[] = { { "A",std::make_unique< A >() },{ "B",std::make_unique< A >() } };

map_type myMap { std::make_move_iterator( begin(elements) ),std::make_move_iterator( end(elements) ) };

这将使myMap迭代范围并移动元素,而不是复制.方法请从this其他问题中获取.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...