考虑下面的代码:为什么复制和移动构造函数一起调用?
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
A(int) { cout << "int" << endl; }
A(A&&) { cout << "move" << endl; }
A(const A&) { cout << "copy" << endl; }
};
int main()
{
vector<A> v
{
A(10), A(20), A(30)
};
_getch();
return 0;
}
输出是:
int
int
int
copy
copy
copy
A(10)
,A(20)
和A(30)
是临时工吧?
那么为什么复制构造函数被调用?不应该调用移动构造函数吗?
传递move(A(10))
,move(A(20))
,move(A(30))
代替,输出为:
int
move
int
move
int
move
copy
copy
copy
在这种情况下,或者复制或移动构造函数被调用。
发生了什么事?
你不能从'initializer_list'元素移动。第二个示例中的附加“移动”禁止复制,因此您可以在复制之上获得额外的移动。 –
好问题;答案埋在这里:http://en.cppreference.com/w/cpp/language/list_initialization – Bathsheba
在一个构造函数中,需要'std :: vector'中的'std :: initializer_list',那些元素不再是右值。 –