为什么 c++ 在以下情况下生成构造函数?
why does c++ generate a constructor in the following case?
我有一个class一个
struct A{
A(){}
A(int x): d(x) {}
A(const A& a): d(a.d) {
std::cout << "copy construction" << std::endl;
}
A(A&& a): d(a.d){
std::cout << "move construction" << std::endl;
}
A& operator=(const A& a){
std::cout << "copy assignment" << std::endl;
d = a.d;
return *this;
}
A& operator=(A&& a){
std::cout << "move assignment" << std::endl;
d = a.d;
return *this;
}
int d;
};
和函数 func
A func(){
return A(3);
}
如果我这样做
A x;
x = func();
输出是预期的 "move assignment"
但是如果我这样构建 A
A x = func();
然后什么都不打印,就好像 c++ 生成了自己的移动构造函数并拒绝使用定义的构造函数。
我正在使用 visual studio 14
我很想了解这个。
感谢您的解释。
省略了构造函数调用。
- 对于 gcc,您可以使用
-fno-elide-constructors
禁用它。
- msvc 没有等效选项。
我有一个class一个
struct A{
A(){}
A(int x): d(x) {}
A(const A& a): d(a.d) {
std::cout << "copy construction" << std::endl;
}
A(A&& a): d(a.d){
std::cout << "move construction" << std::endl;
}
A& operator=(const A& a){
std::cout << "copy assignment" << std::endl;
d = a.d;
return *this;
}
A& operator=(A&& a){
std::cout << "move assignment" << std::endl;
d = a.d;
return *this;
}
int d;
};
和函数 func
A func(){
return A(3);
}
如果我这样做
A x;
x = func();
输出是预期的 "move assignment" 但是如果我这样构建 A
A x = func();
然后什么都不打印,就好像 c++ 生成了自己的移动构造函数并拒绝使用定义的构造函数。
我正在使用 visual studio 14
我很想了解这个。
感谢您的解释。
省略了构造函数调用。
- 对于 gcc,您可以使用
-fno-elide-constructors
禁用它。 - msvc 没有等效选项。