emplace_back, 移动构造的一些事

#include<vector>
#include<string>
#include<iostream>
using namespace std;
struct Persident
{
    string name;
    string country;
    int year;
    int* p;
    Persident(string&& p_name, string&& p_country, int p_year)
        :name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        cout << "I am being constructing" << endl;
        p = new int[23];
    }
    Persident(Persident&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year), p(other.p)
    {
        cout << "I am being move!!!!" << endl;
        other.p = nullptr;
        cout << name.size()<<' '<<other.name.size() << endl;
    }
    ~Persident()
    {
        cout << "I am destorying" << endl;
        cout << name.size() << endl;
        delete p;
    }
};

int main()
{
    vector<Persident> elections;
    cout << "emplace_back" << endl;
    elections.emplace_back("Nel", "Sou", 1994);
    std::vector<Persident> reElections;
    std::cout << "\npush_back:\n";
    reElections.push_back(Persident("Franklin Delano Roosevelt", "the USA", 1936));
    getchar();
    return 0;
}

这段代码输出:

emplace_back
I am being constructing

push_back:
I am being constructing
I am being move!!!!
25 0
I am destorying
0
I am destorying
25
I am destorying
3

 

1. emplace_back直接在vector的堆上构造对象,而不需要经过构造后再移动。所以emplace_back比push_back效率高。

2. 移动构造时,对于字符串string,需要显式调用std::move,否则原string对象不会被移动。但对于指针p,可以不用std::move。但要注意,指针p在移动后需要设为nullptr,否则原指针仍然持有合法对象,在析构时会产生把一个指针delete两次的情况。

posted @ 2017-12-30 11:01  vaevaevae  阅读(509)  评论(0编辑  收藏  举报