vector.emplace_back() 和 vector.push_back() 做同样的事情吗?

Do vector.emplace_back() and vector.push_back() do the same thing?

所以我试图将整数添加到我的向量的背面并错误地认为 push_back() 将新数据添加到向量的前面(也称为向量 [0])。我在 Xcode 中进行了测试,并针对 emplace_back() 测试了 push_back() 并得到了相同的结果。我以为他们是不同的,但这让我觉得也许他们做同样的事情。如果是这样,为什么 vector 有不同的方法?

这是我的代码,以防我正在做的事情:

#include <vector>
#include <iostream> 

using namespace std ;

int main(int argc, const char * argv[])
{
    // for push_back
    vector<int> push;
    push.push_back(1);
    push.push_back(2);
    push.push_back(3);
    push.push_back(4);
    push.push_back(5);
    push.push_back(6);
    //display push_back
    for (int i = 0; i < push.size(); i++) {
        cout << "push[" << i  << "]: " << push[i] << endl;
    }
    // distance between the two funcitons
    cout << endl << endl;

    vector<int> emplace;
    emplace.emplace_back(1);
    emplace.emplace_back(2);
    emplace.emplace_back(3);
    emplace.emplace_back(4);
    emplace.emplace_back(5);
    emplace.emplace_back(6);

    //display emplace_back
    for (int i = 0; i < emplace.size(); i++) {
        cout << "emplace[" << i  << "]: " << emplace[i] << endl;
    }
        return 0;
}

return 是:

push[0]: 1
push[1]: 2
push[2]: 3
push[3]: 4
push[4]: 5
push[5]: 6


emplace[0]: 1
emplace[1]: 2
emplace[2]: 3
emplace[3]: 4
emplace[4]: 5
emplace[5]: 6

我知道这是一个超级简单的问题,但我只是想确保我没有做一些愚蠢的错误并且误解了向量的能力 class。

不同之处在于 emplace_back 将在原地构建对象,而不是复制或移动,cppreference section on std::vector::emplace_back 说:

which typically uses placement-new to construct the element in-place at the location provided by the container. The arguments args... are forwarded to the constructor

这在重物的情况下很重要。我们可以看到这是 original proposal 的动机,它说:

The motivation for placement insert is that containers—especially node-based containers—are very useful for the storage of heavy objects. In some environments efficiency is very important, but there is in general no way to put elements into containers without copying them. A heavy object may store its data directly, in which case move semantics will not improve copy performance. Furthermore, when efficiency is critical the solution cannot depend on compiler optimizations since they are optional and may not occur where they are most needed. Placement insertion lets us create an element once, in the container where we want it, and never have to move it or copy it. It does so in a simple and direct way by introducing new variadic functions that take arguments that are passed on to the element’s constructor using variadic templates and perfect forwarding.

我们可以举一个例子,说明这与 Effective Modern C++ 第 42 条:考虑放置而不是插入 有以下例子:

std::vector<std::string> vs; // container of std::string
vs.push_back("xyzzy"); // add string literal

这会导致创建临时文件,而不是:

vs.emplace_back("xyzzy");

没有。