C++11中,针对顺序容器(如vector、deque、list),新标准引入了三个新成员:emplace_front、emplace和emplace_back,这些操作构造而不是拷贝元素。这些操作分别对应push_front、insert和push_back,允许我们将元素放置在容器头部、一个指定位置之前或容器尾部。

当调用push或insert成员函数时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中。而当我们调用一个emplace成员函数时,则是将参数传递给元素类型的构造函数。emplace成员使用这些参数在容器管理的内存空间中直接构造元素。

emplace函数的参数根据元素类型而变化,参数必须与元素类型的构造函数相匹配。emplace函数在容器中直接构造元素。传递给emplace函数的参数必须与元素类型的构造函数相匹配。

其它容器中,std::forward_list中的emplace_after、emplace_front函数,std::map/std::multimap中的emplace、emplace_hint函数,std::set/std::multiset中的emplace、emplace_hint,std::stack中的emplace函数,等emplace相似函数操作也均是构造而不是拷贝元素。

emplace相关函数可以减少内存拷贝和移动。当插入rvalue,它节约了一次move构造,当插入lvalue,它节约了一次copy构造。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "emplace.hpp"
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <tuple>
#include <utility> namespace emplace_ { /////////////////////////////////////////////////////////
// reference: http://www.cplusplus.com/reference/vector/vector/emplace_back/
int test_emplace_1()
{
{
/*
template <class... Args>
void emplace_back (Args&&... args);
*/
std::vector<int> myvector = { , , }; myvector.emplace_back();
myvector.emplace_back(); std::cout << "myvector contains:";
for (auto& x : myvector)
std::cout << ' ' << x;
std::cout << '\n';
} {
/*
template <class... Args>
iterator emplace (const_iterator position, Args&&... args);
*/
std::vector<int> myvector = { , , }; auto it = myvector.emplace(myvector.begin() + , );
myvector.emplace(it, );
myvector.emplace(myvector.end(), ); std::cout << "myvector contains:";
for (auto& x : myvector)
std::cout << ' ' << x;
std::cout << '\n';
} return ;
} ///////////////////////////////////////////////////////
// reference: http://en.cppreference.com/w/cpp/container/vector/emplace_back
namespace {
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 test_emplace_2()
{
/*
The following code uses emplace_back to append an object of type President to a std::vector.
It demonstrates how emplace_back forwards parameters to the President constructor and shows
how using emplace_back avoids the extra copy or move operation required when using push_back.
*/
std::vector<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_back("Nelson Mandela", "South Africa", ); std::vector<President> reElections;
std::cout << "\npush_back:\n";
reElections.push_back(President("Franklin Delano Roosevelt", "the USA", )); 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";
} return ;
} ////////////////////////////////////////////////////////////////
// reference: https://stackoverflow.com/questions/4303513/push-back-vs-emplace-back
int test_emplace_3()
{
/*
template <class... Args>
pair<iterator,bool> emplace (Args&&... args);
*/
typedef std::tuple<int, double, std::string> Complicated; std::map<int, Complicated> m;
int anInt = ;
double aDouble = 5.0;
std::string aString = "C++"; // cross your finger so that the optimizer is really good
//m.insert(/*std::make_pair*/std::pair<int, Complicated>(4, Complicated(anInt, aDouble, aString)));
m.insert(std::make_pair(, Complicated(anInt, aDouble, aString))); // should be easier for the optimizer
m.emplace(, Complicated(anInt, aDouble, aString));
/*
std::piecewise_construct: This constant value is passed as the first argument to construct a pair object
to select the constructor form that constructs its members in place by forwarding the elements of two
tuple objects to their respective constructor.
*/
m.emplace(std::piecewise_construct, std::make_tuple(), std::make_tuple(anInt, aDouble, aString)); return ;
} //////////////////////////////////////////////////////////////
// reference: https://corecplusplustutorial.com/difference-between-emplace_back-and-push_back-function/
namespace {
class Dat {
int i;
std::string ss;
char c; public:
Dat(int ii, std::string s, char cc) :i(ii), ss(s), c(cc) { } ~Dat() { }
};
} int test_emplace_4()
{
std::vector<Dat> vec;
vec.reserve(); vec.push_back(Dat(, "New", 'G')); // efficiency lesser
//vec.push_back(678, "Newer", 'O'); // error,push_back can’t accept three arguments
vec.emplace_back(, "Newest", 'D'); // work fine, efficiency is also more return ;
} } // namespace emplace_

C++11 vector使用emplace_back代替push_back的更多相关文章

  1. 编程杂谈——使用emplace_back取代push_back

    近日在YouTube视频上看到关于vector中emplace_back与push_back区别的介绍,深感自己在现代C++中还是有不少遗漏的知识点,遂写了段代码,尝试比较两者的差别. 示例代码 #i ...

  2. C++11使用emplace_back代替push_back

    最近在写一段代码的时候,突然很好奇C++11中对push_back有没有什么改进以增加效率,上网搜了一些资料,发现果然新增了emplace_back方法,比push_back的效率要高很多. 首先,写 ...

  3. 学习 emplace_back() 和 push_back 的区别 emplace_back效率高

    在引入右值引用,转移构造函数,转移复制运算符之前,通常使用push_back()向容器中加入一个右值元素(临时对象)的时候,首先会调用构造函数构造这个临时对象,然后需要调用拷贝构造函数将这个临时对象放 ...

  4. 实战c++中的vector系列--emplace_back造成的引用失效

    上篇将了对于struct或是class为何emplace_back要优越于push_back,可是另一些细节没有提及.今天就谈一谈emplace_back造成的引用失效. 直接撸代码了: #inclu ...

  5. vector 类中的 push_back( ) 函数

    函数名 push_back,算法语言里面的一个函数名,如:   1) c++中的vector头文件里面就有这个push_back函数:   2) 在vector类中作用为在vector尾部加入一个数据 ...

  6. (转)C++11使用emplace_back代替push_back (其中有关于右值引用)

    最近在写一段代码的时候,突然很好奇C++11中对push_back有没有什么改进以增加效率,上网搜了一些资料,发现果然新增了emplace_back方法,比push_back的效率要高很多. 首先,写 ...

  7. C++ std::vector emplace_back 优于 push_back 的理由

    #include <iostream> #include <vector> #include <chrono> #include <windows.h> ...

  8. emplace_back与push_back的区别

    std::vector::emplace_back     C++   Containers library   std::vector   template< class... Args &g ...

  9. 【C/C++开发】emplace_back() 和 push_back 的区别

    在引入右值引用,转移构造函数,转移复制运算符之前,通常使用push_back()向容器中加入一个右值元素(临时对象)的时候,首先会调用构造函数构造这个临时对象,然后需要调用拷贝构造函数将这个临时对象放 ...

随机推荐

  1. MMU内存管理单元

    arm-linux学习-(MMU内存管理单元) 什么是MMU MMU(Memory Management Unit)主要用来管理虚拟存储器.物理存储器的控制线路,同时也负责虚拟地址映射为物理地址,以及 ...

  2. centos 环境搭建jenkins服务

    1.下载jenkins war包 https://jenkins.io/download/ 选择Generic Java package (.war)下载2.下载apache tomcat 8 htt ...

  3. Effective Java 第三版笔记(目录)

    <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将近8年的时 ...

  4. Python(字符编码)

    https://www.cnblogs.com/zihe/p/6993891.html 一 了解字符编码的知识储备 1. 文本编辑器存取文件的原理(nodepad++,pycharm,word) 打开 ...

  5. 蜕变成蝶~Linux设备驱动之中断与定时器

    “我叮咛你的 你说 不会遗忘 你告诉我的 我也全部珍藏 对于我们来说 记忆是飘不落的日子 永远不会发黄 相聚的时候 总是很短 期待的时候 总是很长 岁月的溪水边 捡拾起多少闪亮的诗行 如果你要想念我  ...

  6. 使用100%面向过程的思维方式来写java程序

    1.java是强制写class关键字的语言,不能有独立的函数游离在类外出现在文件中,这和python c++ 都不同,后面的都可以单独在类外写函数,所以java被称为是纯面向对象的语言,py和c++都 ...

  7. 使用 ES2015 编写 Gulp 构建

    Gulp 自 v3.9.0 版本增加对 Babel 的支持,也就是说可以使用 ES2015 语法来编写 gulp 任务. 检查 gulp 版本 $ gulp -v 确保 gulp-cli 和 gulp ...

  8. PHP 通过构造器进行依赖注入 demo

    class A{ public $b; public $f; function __construct( B $b , $f = 1 ){ $this->b = $b; $this->f ...

  9. Golang 笔记 2 函数、结构体、接口、指针

    一.函数 Go中函数是一等(first-class)类型.我们可以把函数当作值来传递和使用.Go中的函数可以返回多个结果.  函数类型字面量由关键字func.由圆括号包裹声明列表.空格以及可以由圆括号 ...

  10. Qt自定义控件大全+designer源码

    抽空将自定义控件的主界面全部重写了一遍,采用左侧树状节点导航,看起来更精美高大上一点,后期准备单独做个工具专用每个控件的属性设计,其实qt自带的designer就具备这些功能,于是从qt4的源码中抽取 ...