【发布时间】:2018-02-22 18:11:58
【问题描述】:
您好,我正在尝试了解在 C++ 中传递对象的基础知识,并且我了解当将对象传递给函数时,会调用该对象的复制构造函数,如果函数返回一个对象,则会调用移动构造函数回归主线。我也理解如果一个对象超出范围,它们会被析构函数破坏。但是,我的程序中似乎有一个额外的析构函数。
输出:
Top of Program
Constructors here
Constructor
Constructor
End of Constructors
BoxSendReturn function
Copy Constructor
Inside BoxSendReturn
Move Constructor
Move Assignment
Destructor
Destructor
Destructor
End of Box Send Return
Destructor
Destructor
代码如下:
enter code here
#include<iostream>
using namespace std;
class Box{
private:
public:
Box(){ cout<<"Constructor"<<endl; }
~Box(){ cout<<"Destructor"<<endl; }
Box (const Box &other) { cout<<"Copy Constructor"<<endl; }
Box (Box &&other) { cout<<"Move Constructor"<<endl; }
Box operator=(const Box &other){ cout<<"Copy Operator"<<endl; }
Box operator=(Box &&other){ cout<<"Move Assignment"<<endl;}
};
Box BoxSendReturn(Box b){
cout<<"Inside BoxSendReturn"<<endl;
return b;
}
int main(){
cout<<"Top of Program"<<endl;
cout<<"Constructors here"<<endl;
Box b1, b2;
cout<<"End of Constructors"<<endl;
cout<<"BoxSendReturn function"<<endl;
b1 = BoxSendReturn(b2);
cout<<"End of Box Send Return"<<endl;
return 0;
}
【问题讨论】:
-
您的程序中有 UB,您的分配运算符不返回任何内容,顺便说一句,它们通常返回引用,而不是按值
-
除了未定义的行为之外,如果您在输出语句中显示
this的值,而不仅仅是正在执行的操作,将会更有帮助。这样你就会知道创建/销毁哪个对象,以及以什么顺序。 -
感谢您解决了问题!
标签: c++