好像这段代码:
#include <string>
#include <vector>
struct bla
{
std::string a;
int b;
};
int main()
{
std::vector<bla> v;
v.emplace_back("string", 42);
}
Run Code Online (Sandbox Code Playgroud)
可以在这种情况下正常工作,但它没有(我理解为什么).给bla构造函数解决了这个问题,但是删除了类型的聚合性,这可能会产生深远的影响.
这是标准中的疏忽吗?或者我错过了某些会在我脸上爆炸的情况,或者它不像我想的那么有用?
这与我之前提出的关于emplace_back在成对向量上使用的问题有些相关。将一对插入 std::vector 时,emplace_back() 与 push_back
现在我的问题与emplace_back在向量向量上使用有关。
这是我用评论质疑的代码
std::vector<std::vector<int>> matrix;
matrix.emplace_back({1,2,3}); //doesn't compile
matrix.emplace_back(1,2,3); //doesn't compile
matrix.push_back({1,2,3}); //works and does what is expected (insert a vector made of {1,2,3} into matrix);
matrix.emplace_back(std::vector<int>{1,2,3}); //works but
//defeats the purpose of using emplace_back since this makes a copy
//and is thus equivalent to push_back in this case?
matrix.emplace_back(3,2) //this compiles,
//but it seems to insert a vector of size 3 made of 2s into the matrix.
//not actually sure …Run Code Online (Sandbox Code Playgroud)