TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

emplace_back

参考

push_back和emplace_back

emplace_back

函数定义

1
2
3
4
5
6
7
8
9
10
11
12
//c++11 -- c++17
template< class... Args >
void emplace_back( Args&&... args );

//since c++17
template< class... Args >
reference emplace_back( Args&&... args );

void push_back( const T& value );
//since c++11
void push_back( T&& value );

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// vector::emplace
#include <iostream>
#include <vector>

int main ()
{
std::vector<int> myvector = {10,20,30};

auto it = myvector.emplace ( myvector.begin()+1, 100 );
myvector.emplace ( it, 200 );
myvector.emplace ( myvector.end(), 300 );

std::cout << "myvector contains:";
for (auto& x: myvector)
std::cout << ' ' << x;
std::cout << '\n';

return 0;
}

example

input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <vector>
#include <string>
#include <iostream>

struct President
{
std::string name;
std::string country;
int year;

President(std::string p_name, std::string p_country, int p_year)
: name(std::move(p_name)), country(std::move(p_country)), year(p_year)
{
std::cout << "I am being constructed.\n";
}
President(President&& other)
: name(std::move(other.name)), country(std::move(other.country)), year(other.year)
{
std::cout << "I am being moved.\n";
}
President& operator=(const President& other) = default;
};

int main()
{
std::vector<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_back("Nelson Mandela", "South Africa", 1994);

std::vector<President> reElections;
std::cout << "\npush_back:\n";
reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));

std::cout << "\nContents:\n";
for (President const& president: elections) {
std::cout << president.name << " was elected president of "
<< president.country << " in " << president.year << ".\n";
}
for (President const& president: reElections) {
std::cout << president.name << " was re-elected president of "
<< president.country << " in " << president.year << ".\n";
}
}

output

emplace_back:
I am being constructed.

push_back:
I am being constructed.
I am being moved.

Contents:
Nelson Mandela was elected president of South Africa in 1994.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.

总结

c++11以后push_back也支持右值引用了,但和emplace_back的区别是:emplace_back支持可变参数列表的形式,可以在括号内直接赋值:

elections.emplace_back("Nelson Mandela", "South Africa", 1994);

而push_back必须有一个具体的实现(临时对象),看得到的参数来匹配对应的拷贝构造函数,operator=函数:

reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));

push_back创建了一个临时对象President,然后通过移动构造函数把临时对象移动过来。而emplace直接通过括号的值来初始化对象。一步到位。

ending

82157620_p0_master1200.jpg

----------- ending -----------