请考虑以下代码:
#include<iostream>
using namespace std;
struct A {
A(const A&){
cout<<"copy constructor"<<endl;
}
A(A&&){
cout<<"move constructor"<<endl;
}
~A(){
cout<<"destructor"<<endl;
}
static std::pair<A,int> f1()
{
int i = 1;
return std::pair<A,int>{i,2};
}
static std::pair<A,int> f2()
{
int i = 1;
return std::pair<A,int>{A(i),2};
}
private:
A(int){
cout<<"constructor"<<endl;
}
};
int main()
{
cout<<"f1: "<<endl;
A::f1();
cout<<"f2: "<<endl;
A::f2();
}
构造函数
A(int)
是私有的,因此pair<A,int>
中的A
不能从int
直接构建。因此,在f1
中会构造一个临时变量。在f2
中,我明确地创建了临时变量,但行为不同,输出结果如下:f1:
constructor
copy constructor
destructor
destructor
f2:
constructor
move constructor
destructor
destructor
我本期望在 A::f1
中也调用移动构造函数,但实际上调用了拷贝构造函数,这是次优的。为什么会出现这种情况?
A(int)
设为explicit A(int)
而不是私有的。这样你就可以得到更好的输出f1: \nconstructor\ndestructor
。 - 273K