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

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

概述我有以下代码,不会编译,它是星期五,我有点疲惫. #include <string>#include <memory>#include <utility>#include <map>template< typename T, typename ...Args >std::unique_ptr< T > make_unique( Args && ...args ){ retur 我有以下代码,不会编译,它是星期五,我有点疲惫.
#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其他问题中获取.

总结

以上是内存溢出为你收集整理的存储在std :: map里面的C std :: unique_ptr使用了被删除的函数ill形成的全部内容,希望文章能够帮你解决存储在std :: map里面的C std :: unique_ptr使用了被删除的函数ill形成的所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1238712.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存