我有这堂课:
class Foo {
public:
Foo() {}
Foo(const Foo&){cout << "constructed by lvalue reference." <<endl; }
Foo(Foo&& ) {cout << "constructed by rvalue reference." << endl; }
};
然后我插入一个向量:
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.