c++ - 为什么 vector::push_back 和 emplace_back 调用 value_type::constructor 两次?

标签 c++ c++11

我有这门课:

class Foo {
public:
    Foo() {}
    Foo(const Foo&){cout << "constructed by lvalue reference." <<endl; }
    Foo(Foo&& ) {cout << "constructed by rvalue reference." << endl; }
};

然后我插入一个 vector :

Foo foo{};
vf.push_back(foo);

输出令人惊讶:

constructed by lvalue reference.
constructed by lvalue reference.

我假设它在传递参数时被复制了,所以我尝试了:

vf.push_back(move(foo));

vf.push_back(forward<Foo>(foo));

由于移动语义,输出略有不同,但仍然调用了两次构造函数:

constructed by rvalue reference.
constructed by lvalue reference.

为什么构造函数被调用了两次?它对性能有多大影响?我怎样才能避免这种情况?


我在 Windows Vista 上使用 mingw-gcc-4.7.1

总例:

#include <iostream>
#include <vector>

using namespace std;

class Foo {
public:
    Foo() {}
    Foo(const Foo&){cout << "constructed by lvalue reference." <<endl; }
    Foo(Foo&& ) {cout << "constructed by rvalue reference." << endl; }
};


int main(int argc, char **argv, char** envp)
{
    vector<Foo> vf;
    cout << "Insert a temporary." << endl;
    vf.emplace_back(Foo{});

    Foo foo{};
    cout << "Insert a variable." << endl;
    vf.emplace_back(foo);

    return 0;
}

精确输出:

Insert a temporary.
constructed by rvalue reference.
Insert a variable.
constructed by lvalue reference.
constructed by lvalue reference.

最佳答案

当您在 vector 中插入新项目时, vector 可能必须分配更多内存以适应这些对象。发生这种情况时,它需要将所有元素复制到新的内存位置。这将调用复制构造函数。因此,当您插入元素时,您将获得该新元素的构造函数和复制前一个元素时的构造函数。

关于c++ - 为什么 vector::push_back 和 emplace_back 调用 value_type::constructor 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260686/

相关文章:

C++ 生日概率

c++ - 如何在PCL获取相机参数?

c++ - 是否可以根据整数模板参数构造成员数组的元素?

c++ - 两次删除函数声明的区别

c++ - 混合模板与 std::enable_if_t 和特化

c++ - 使用可变参数模板构建元组

c++ - 一个只接受枚举类型参数的模板类?

c++ - 如何在 VC++/MFC 应用程序中根据当前 DPI 设置缩放字体大小?

java, System.loadlibrary ("someDLLFile") 获取未统计的链接错误

c++ - 没有类的对象 - 'clean C' 中的数据模型