zoukankan      html  css  js  c++  java
  • 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 只调用了构造函数

  • 相关阅读:
    Codeforces Round #313 (Div. 1) A.Gerald's Hexagon
    COJN 0585 800604鸡蛋的硬度
    COJN 0584 800603吃糖果
    COJN 0583 800602分苹果
    COJN 0575 800601滑雪
    昨天的补记
    重构的代码
    写了一个复杂的sql语句
    一个想法
    安装了C
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/14692951.html
Copyright © 2011-2022 走看看