gpt4 book ai didi

c++ - emplace_back 没有创建就地对象

转载 作者:搜寻专家 更新时间:2023-10-31 00:25:55 25 4
gpt4 key购买 nike

    #include <iostream>
#include<vector>
using namespace std;

class test{
public:
test(){
cout<<"constructor called"<<endl;
}
test(const test& obj){
cout<<"copy constructor called"<<endl;
}
test(test&& obj){
cout<<"Move constructor called"<<endl;
}
};
int main()
{
vector<test> vec;
vec.emplace_back(test());

return 0;
}

当我运行上面的程序时,我希望 emplace_back 在 vector 中就地创建对象。因此应该输出“调用的构造函数”,因为 emplace_back 会避免创建临时对象。

但是输出是:

constructor called
Move constructor called

在这里,临时对象的创建就像 push_back 一样。请解释。

最佳答案

emplace_back不构造临时对象,但您通过 test() 显式构造了一个临时对象,然后通过移动构造函数将新元素从临时对象添加到 vector

你可以

vec.emplace_back();

关于c++ - emplace_back 没有创建就地对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54546530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com