栈堆的emplace和push_3个例子详解C++ 11 中push_back 和 emplace_back差异

cpp11 pushback and emplaceback

Guide

case1

#include

#include

class A

{

public:

A (int x_arg) : x (x_arg) { std::cout << "A (x_arg)\n"; }

A () { x = 0; std::cout << "A ()\n"; }

A (const A &rhs) noexcept { x = rhs.x; std::cout << "A (A &)\n"; }

A (A &&rhs) noexcept { x = rhs.x; std::cout << "A (A &&)\n"; }

~A() { std::cout << "~A ()\n"; }

private:

int x;

};

void test_emplace_back_1()

{

// For emplace_back constructor A (int x_arg) will be called.

// And for push_back A (int x_arg) is called first and

// move A (A &&rhs) is called afterwards

{

std::vector a;

std::cout << "call emplace_back:\n";

a.emplace_back(0);

// (1) direct object creation inside vector

}

{

std::vector a;

std::cout << "call push_back:\n";

a.push_back(1);

// (1) create temp object and

// (2) then move copy to vector and

// (3) free temp object

}

}

/*

call emplace_back:

A (x_arg)

~A ()

call push_back:

A (x_arg)

A (A &&)

~A ()

~A ()

*/复制代码

see

759b504f3a71ebb8637e11008530d542.png

case2

void test_emplace_back_2()

{

// emplace_back and push_back for `A(0)`, it's same.

// A (int x_arg) is called first and

// move A (A &&rhs) is called afterwards

{

std::vector a;

std::cout << "call emplace_back:\n";

a.emplace_back(A(0));

// (1) create temp object and

// (2) then move copy to vector and

// (3) free temp object

}

{

std::vector a;

std::cout << "call push_back:\n";

a.push_back(A(1));

// (1) create temp object and

// (2) then move copy to vector and

// (3) free temp object

}

}

/*

call emplace_back:

A (x_arg)

A (A &&)

~A ()

~A ()

call push_back:

A (x_arg)

A (A &&)

~A ()

~A ()

*/复制代码

case 3

void test_emplace_back_3()

{

// emplace_back and push_back for `A obj(0)`, it's same.

// A (int x_arg) is called first and

// copy constructor A (A &) is called afterwards

{

std::vector a;

std::cout << "call emplace_back:\n";

A obj(0);

a.emplace_back(obj);

// copy constructor to vector

}

{

std::vector a;

std::cout << "call push_back:\n";

A obj(1);

a.push_back(obj);

// copy constructor to vector

}

}

/*

call emplace_back:

A (x_arg)

A (A &)

~A ()

~A ()

call push_back:

A (x_arg)

A (A &)

~A ()

~A ()

*/复制代码

Reference

History

20190422: created.

Copyright

Post author: kezunlin

Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值