C++ 为什么不调用我的复制构造函数?
可能重复:C++ 为什么不调用我的复制构造函数?,c++,operator-overloading,copy-constructor,C++,Operator Overloading,Copy Constructor,可能重复: 我有以下计划: #include <iostream> using namespace std; class Pointt { public: int x; int y; Pointt() { x = 0; y = 0; cout << "def constructor called" << endl; } Pointt(int x, int y) {
我有以下计划:
#include <iostream>
using namespace std;
class Pointt {
public:
int x;
int y;
Pointt() {
x = 0;
y = 0;
cout << "def constructor called" << endl;
}
Pointt(int x, int y) {
this->x = x;
this->y = y;
cout << "constructor called" << endl;
}
Pointt(const Pointt& p) {
this->x = p.x;
this->y = p.y;
cout << "copy const called" << endl;
}
Pointt& operator=(const Pointt& p) {
this->x = p.x;
this->y = p.y;
cout << "op= called" << endl;
return *this;
}
};
Pointt func() {
cout << "func: 1" << endl;
Pointt p(1,2);
cout << "func: 2" << endl;
return p;
}
int main() {
cout << "main:1" << endl;
Pointt k = func();
cout << "main:2" << endl;
cout << k.x << " " << k.y << endl;
return 0;
}
但我得到了以下信息:
main:1
func: 1
constructor called
func: 2
copy const called
op= called
main:2
1 2
main:1
func: 1
constructor called
func: 2
main:2
1 2
问题是:为什么不将对象从func返回到main调用我的复制构造函数?这是由于。这是C++中允许为优化改变程序行为的少数实例之一。我理解为什么您希望复制构造函数被调用,但是您不应该期望调用赋值操作符。当初始化中使用“
=
”时,它实际上不是赋值运算符,而是复制初始化(在本例中优化了)。如果没有优化,将有2个对复制构造函数的调用。