拷贝构造函数调用的几种情况(笔记)

头文件:

#ifndef  _TEST_H_
#define _TEST_H_

class Test
{
public:
	Test();
	explicit Test(int num);
	Test(const Test& other);
	void Display();
	Test& Test::operator=(const Test& other);

	~Test();	//析构函数不能够被重载
private:
	int num_;
};

#endif	//_TEST_H_
测试代码:

#include "Test.h"
#include <iostream>
using namespace std;

void TestFun(const Test t)
{

}

void TestFun2(const Test& t)
{

}

Test TestFun3(const Test& t)
{
	return t;
}
const Test& TestFun4(const Test& t)
{
	return t;
}
int main(void)
{

	Test t(10);
	TestFun(t);
	TestFun2(t);
	t = TestFun3(t);
	Test t2 = TestFun3(t);
	Test& t3 = TestFun3(t);
	Test t4 = TestFun4(t);
	const Test& t5= TestFun4(t);
	
	cout<<"...."<<endl;
	return 0;
}
Test t(10) :初始化

TestFun(t):实参初始化形参,调用拷贝构造好函数

TestFun2(t):传递引用,和实参共享同块内存,不会调用拷贝构造函数,建议参数传递时用引用传递,减少内存占用

TestFun3(t):函数返回的是对象,系统会创建一个临时对象返回给调用者,会调用拷贝构造函数,如果临时对象没有接收者,所以立即销毁

t = TestFun3(t):。。。有接收者,不会立即销毁

Test t2 = TestFun3(t):不会调用拷贝构造函数,把临时对象改名为t2

Test& t3 = TestFun3(t):无效的引用,不会马上销毁

Test t4 = TestFun4(t):对象的引用初始化t4,会调用拷贝构造函数

const Test& t5 = TestFun4(t):传递引用,不会调用拷贝构造函数



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值