实验代码:
class A {
public:
A(int x) {
x = x;
cout << "construct A" << endl;
}
A(const A& a) {
x = a.x;
cout << "copy construct A" << endl;
}
A(const A&& a) {
cout << "Move construct A" << endl;
}
private:
int x;
};
int main()
{
vector<A> vec;
vector<A> vec2;
cout << endl << "emplace" << endl;
vec.emplace_back(1);
cout << endl << "push" << endl;
vec2.push_back(1);
运行结果:
在定义了A的移动构造函数的时候

注释掉A的移动构造函数后

结果:
push_back会在有移动构造函数时优先使用移动构造,没有移动构造就使用拷贝构造。
emplace_back只进行一次构造。

当A类有移动构造函数时,push_back会优先使用移动构造,无移动构造则用拷贝构造。emplace_back始终仅调用一次构造函数。实验展示了这两个方法在对象插入向量时的行为差异。
247

被折叠的 条评论
为什么被折叠?



