emplace_back 使用零拷贝添加元素验证

对于push_back和emplace_back在数组尾后添加元素的区别:

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

struct Person{
    string name;
    int age;

    //初始构造函数
    Person(string p_name, int p_age):name(std::move(p_name)), age(p_age){
        cout << "I have been constructed" << endl;
    }

    //拷贝构造函数
    Person(const Person& other) : name(std::move(other.name)), age(other.age){
        cout << "I have been copy constructed" << endl;
    }

    //转移构造函数
    Person(Person&& other):name(std::move(other.name)), age(other.age){
        cout << "I have been moved" << endl;
    }
};

int main(){
    vector<Person> e;
    cout << "emplace_back: " << endl;
    e.emplace_back("jane", 23); //不用构造类函数

    vector<Person> p;
    cout << "push_back " << endl;
    p.push_back(Person("mike", 36));
    return 0;
}

运行结果显示(自测):

  push_back 调用了构造函数和移动构造函数,emplace_back 只调用了构造函数

原文地址:https://www.cnblogs.com/wanghao-boke/p/14692951.html