首页 > 解决方案 > C++ std::vector::emplace_back 不能用字符串值类编译

问题描述

/* Item.h */
struct Item {
    std::string name;

    Item(std::string _name) : name( std::move(_name) ) { }
};

/* main.cpp */
/* ... */
const int amount_of_items = val.size();
std::vector<Item> items(amount_of_items);

for( Json::Value::const_iterator itr = val.begin() ; itr != val.end() ; ++itr ) {
    items.emplace_back( "item_name" );
}

结果是:

/usr/include/c++/8/bits/stl_construct.h:75:7: error: no matching function for call to ‘Item::Item()’
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from main.cpp:8: Item.h:8:2: note: candidate: ‘Item::Item(std::__cxx11::string)’   Item(std::string _name) : name( std::move(_name) ) { }   ^~~~ Item.h:8:2: note:   candidate expects 1 argument, 0 provided

我不知道为什么这行不通-有什么想法吗?

标签: c++perfect-forwarding

解决方案


这个说法:

std::vector<Item> items(amount_of_items);

需要默认构造函数,因为您已要求编译器使用默认构造的 sItem填充数组。amount_of_itemsItem

相反,您需要简单地编写:

std::vector<Item> items;

因为emplace_back将根据需要增加数组。

请注意,如果您想预先为您的 s 预留空间,您可以致电。items.reserveItem


推荐阅读