gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:58:55 28 4
gpt4 key购买 nike

我有这门课:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com