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两次的情况。

转载于:https://www.cnblogs.com/vaecn/p/8149071.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值