c++ - push_back vs emplace_back

标签 c++ visual-studio-2010 stl c++11 move-semantics

我对 push_backemplace_back 之间的区别有点困惑。

void emplace_back(Type&& _Val);
void push_back(const Type& _Val);
void push_back(Type&& _Val);

由于有一个 push_back 重载采用右值引用,我不太明白 emplace_back 的目的是什么?

最佳答案

除了访客所说的:

函数void emplace_back(Type&& _Val) MSCV10 提供的不符合标准和冗余,因为正如您所指出的,它严格等同于 push_back(Type&& _Val) .

但是emplace_back 的真正C++0x 形式真的很有用: void emplace_back(Args&&...) ;

而不是采取value_type它需要一个可变参数列表,这意味着您现在可以完美地转发参数并将对象直接构造到容器中,而根本不需要临时参数。

这很有用,因为无论 RVO 和 move 语义带来了多少聪明才智,仍然存在一些复杂的情况,即 push_back 可能会进行不必要的复制(或 move )。例如,使用传统的 insert() std::map 的功能,您必须创建一个临时文件,然后将其复制到 std::pair<Key, Value> ,然后将其复制到 map 中:

std::map<int, Complicated> m;
int anInt = 4;
double aDouble = 5.0;
std::string aString = "C++";

// cross your finger so that the optimizer is really good
m.insert(std::make_pair(4, Complicated(anInt, aDouble, aString))); 

// should be easier for the optimizer
m.emplace(4, anInt, aDouble, aString);

那么为什么他们没有在 MSVC 中实现正确版本的 emplace_back 呢?其实前段时间我也被它打扰了,所以我在 Visual C++ blog 上问了同样的问题。 .这是来自微软 Visual C++ 标准库实现的官方维护者 Stephan T Lavavej 的回答。

Q: Are beta 2 emplace functions just some kind of placeholder right now?

A: As you may know, variadic templates aren't implemented in VC10. We simulate them with preprocessor machinery for things like make_shared<T>(), tuple, and the new things in <functional>. This preprocessor machinery is relatively difficult to use and maintain. Also, it significantly affects compilation speed, as we have to repeatedly include subheaders. Due to a combination of our time constraints and compilation speed concerns, we haven't simulated variadic templates in our emplace functions.

When variadic templates are implemented in the compiler, you can expect that we'll take advantage of them in the libraries, including in our emplace functions. We take conformance very seriously, but unfortunately, we can't do everything all at once.

这是一个可以理解的决定。每个尝试过一次用预处理器可怕的技巧模拟可变参数模板的人都知道这些东西有多恶心。

关于c++ - push_back vs emplace_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4303513/

相关文章:

c++ - 如何在opengl中改变物体相对相机的位置?

c++ - 如何将函数集合传递给客户端类以将它们用作客户端类本身的成员?

c++ - 什么时候应该在堆栈而不是堆上分配一个类

c++ - 错误 MSB6006 : "cmd.exe" exited with code

c++ - 为什么 vector 的随机访问迭代器与指针不同,给出相同的内存地址?

c++ - 使用类方法插入 std::map

c++ - 具有多个客户端的服务器 : how to forward message from one client to another

C#:将 DllImport 与继承相结合?

.net - .NET 3.5 的代码契约搞乱了 VS10 的调试器

STL - 在 C++ 中,当键是带字符串的结构时,如何在带有仿函数的映射上使用 find_if?