首页 > 代码库 > ch02

ch02

 

 

 

 

2.4 emplace_back减少内存拷贝

 

 

 

#include <vector>
#include <map>
#include <string>
#include <iostream>

using namespace std;

struct Complicated
{
    int year;
    double country;
    std::string name;

    Complicated(int a, double b, std::string c) :year(a), country(b), name(c)
    {
        cout << "is conrtusted" << endl;
    }
    
    Complicated(const Complicated & other)
        : year(other.year)
        , country(other.country)
        , name(std::move(other.name))
    {
        cout << "is moved" << endl;
    }
};

int main()
{
    std::map<int, Complicated> m;
    int aInt = 4;
    double aDouble = 5.0;
    std::string aString = "C++";
    cout << "--insert--" << endl;

    m.insert(std::make_pair(4, Complicated(aInt, aDouble, aString)));

    cout << "--emplace--" << endl;
    m.emplace(4, Complicated(aInt, aDouble, aString));

    cout << "--emplce_back--" << endl;
    vector<Complicated> v;
    v.emplace_back(aInt, aDouble, aString);
    cout << "--push_back--" << endl;
    v.push_back(Complicated(aInt, aDouble, aString));

    system("pause");
}

运行结果:

技术分享

ch02