1.赋值与复制
c++中调用拷贝构造函数的情形大概有三种:BOX newbox = mybox或者BOX newbox(mybox), 函数传参以及返回值返回对象时
而赋值则是对已经存在的同类对象之间用赋值符号"="
相关的博客为:https://www.cnblogs.com/NongSi-Net/p/4262265.html
2.函数return的机制
以前学习c语言的时候虽然了解return的机制, 但是没能通过代码的角度真正观察到, 现在学习了c++的this指针,可以一看究竟
总结一下:函数return的时候会先开辟一块临时内存, 把返回值拷贝到临时内存中, 再把临时内存中的返回值拷贝到接收函数返回值的内存中, 完成之后临时内存销毁
3.以下代码时学习过程中的记录
【注意】:-fno-elide-constructors是防止g++编译器优化, 能让我们看到return时拷贝构造函数的调用
root@ubuntu:/lianxi/lianxi_c++/chongzai# g++ -fno-elide-constructors erYuanChongZai.cpp -o b.out
root@ubuntu:/lianxi/lianxi_c++/chongzai# ./b.out
call constructor this = 0xbfe4fd08
this->length = 15 this->width = 15 this = 0xbfe4fd08
call constructor this = 0xbfe4fd18
this->length = 5 this->width = 5 this = 0xbfe4fd18
call copy-constructor this = 0xbfe4fd10
call destroyer this = 0xbfe4fd18
call constructor this = 0xbfe4fd20
this->length = 7 this->width = 8 this = 0xbfe4fd20
&box1 = 0xbfe4fd08
&box2 = 0xbfe4fd10
&box3 = 0xbfe4fd20
calling overload Func this = 0xbfe4fd08
call constructor this = 0xbfe4fcd8
this->length = 1 this->width = 3 this = 0xbfe4fcd8
call copy-constructor this = 0xbfe4fcd0
call destroyer this = 0xbfe4fcd8
call overload Func over!
call copy-constructor this = 0xbfe4fd28
call destroyer this = 0xbfe4fcd0
call destroyer this = 0xbfe4fd28
area:225
area:25
area:9
call destroyer this = 0xbfe4fd20
call destroyer this = 0xbfe4fd10
call destroyer this = 0xbfe4fd08
root@ubuntu:/lianxi/lianxi_c++/chongzai#
#include <iostream>
using namespace std;
class BOX
{
private:
int length;
int width;
public:
/*constructor*/
BOX(int len = 0, int wid = 0):length(len), width(wid)
{
cout << "call constructor this = " << this <<endl;
cout << "this->length = " << this->length << " this->width = " << this->width << " this = " << this << endl;
//cout << "\n";
}
/*copy-constructor*/
BOX(const BOX &someBox)
{
cout << "call copy-constructor this = " << this <<endl;
//cout << "\n";
this->length = someBox.length;
this->width = someBox.width;
}
/*destroyer*/
~BOX(void)
{
cout << "call destroyer this = " << this << endl;
//cout << "\n";
}
void getArea(void)
{
cout << "area:" << (this->length) * (this->width) << endl;
//cout << "\n";
return;
}
/*overload "/"*/
BOX operator /(BOX &someBox)
{
cout << "calling overload Func this = " << this <<endl;
//cout << "\n";
//BOX tempBox;
BOX tempBox = BOX(1, 3);
tempBox.length = (this->length) / (someBox.length);
tempBox.width = (this->width) / (someBox.width);
cout << "call overload Func over!" << endl;
//cout << "\n";
return (tempBox);
}
};
int main(void)
{
BOX box1(15, 15);
BOX box2 = BOX(5, 5);
BOX box3(7, 8);
cout << "&box1 = " << &box1 << endl;
cout << "&box2 = " << &box2 << endl;
cout << "&box3 = " << &box3 << endl;
//cout << "\n";
box3 = box1 / box2;
box1.getArea();
box2.getArea();
box3.getArea();
return 0;
}