微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

存储在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其他问题中获取.

原文地址:https://www.jb51.cc/c/118003.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐