【发布时间】:2021-10-12 08:31:17
【问题描述】:
我知道这个问题被问了很多,我看到很多解释都引用了“emplace_back 构造,push_back() 构造和复制”。有些帖子问为什么 emplace_back 调用复制构造函数,因为它们没有为向量保留内存。
但是对于以下情况,我无法弄清楚 emplace_back() 比 push_back() 实现的更多。一些答案说“你需要为 emplace_back() 实现移动构造函数”但是 push_back() 也可以利用移动构造函数。那么有什么区别
#include <iostream>
#include <vector>
using namespace std;
class Int{
public:
int* p;
Int(int x): p(new int(x)) {cout<<"constructor called for "<<*p<<endl;}
Int(const Int& x): p(new int(*(x.p))) {cout<<"copy constructor called for "<<*p<<endl;}
~Int(){
if (p!= nullptr) {cout<<"destructor called for "<<*p<<endl;}
else{cout<<"destructor called for null ptr"<<endl;}
delete p;
}
Int(Int&& x): p(x.p) {
x.p = nullptr;
cout<<"move constructor called for "<<*p<<endl; // move constructor, remove to test emplace_back()
}
};
int main(){
vector<Int> v;
v.reserve(1);
v.emplace_back(Int(1)); // can switch to push_back()
// v.push_back(Int(1));
cout<<"end program"<<endl;
}
对我来说,这两种方法似乎都调用了没有移动构造函数的复制构造函数,如果有,则调用移动构造函数。
【问题讨论】:
-
v.emplace_back(1);
标签: c++ stdvector rvalue-reference move-constructor emplace