Sca*_*ark 8 c++ dictionary unique-ptr
我有以下代码,不会编译,它是星期五,我有点疲惫.
#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!!
Run Code Online (Sandbox Code Playgroud)
以下编译没有问题
int main()
{
std::pair< std::string, std::unique_ptr< A > > p { "B", make_unique< A >() };
_map.insert( std::make_pair( "C", make_unique< A >() ) );
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是(粗略地,删除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.
Run Code Online (Sandbox Code Playgroud)
Argghh!请阅读c ++ 11标准中的内容.
当初始化程序列表初始化聚合时,如8.5.4中所述,初始化程序列表的元素将作为聚合成员的初始化程序,增加下标或成员顺序.每个成员都是从相应的initializer子句复制初始化的
无赖!
任何人都知道初始化列表是否完全不可能?
您无法做很多事情:复制初始化列表中的元素.这不会与仅移动的类相处.
有一种方法可以绕过这个"缺陷",但阅读并不是很好; 你决定
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) ) };
Run Code Online (Sandbox Code Playgroud)
这将使myMap范围内的迭代并移动元素,而不是复制.方法请从这个其他问题中获取.