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

来源:互联网 发布:关于网络舆论的论文 编辑:程序博客网 时间:2024/06/05 00:19

头文件:

#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