C++中深拷贝与浅拷贝的区别

#include<iostream>

using namespace std;

class c_Example {
private:
	int a;
public:
	c_Example()//默认构造函数
	{
	}
	c_Example(int b)//自定义构造函数
	{
		a = b;
	}
	c_Example(const c_Example& A)//自定义拷贝构造函数
	{
		a = A.a;
	}
	void show()
	{
		cout << a << endl;
	}
};
class deep_Example {
private:
	int a;
	char *str;
public:
	deep_Example(int b,const char *cstr)
	{
		a = b;
		str = new char[b];
		strcpy(str, cstr);
	}
	~deep_Example()
	{
		cout << "xigou" << endl;
	}
	deep_Example(const deep_Example& A)//深拷贝,重新分配一块新的内存
	{
		a = A.a;
		str = new char[a];
		if (str != 0)
		{
			strcpy(str, A.str);
		}
	}
	void show()
	{
		cout << str << endl;
		cout << a << endl;
	}
	deep_Example()
	{
		delete str;
	}
};


int main()
{
	/*
	如果没有显示声明一个拷贝构造函数,系统将会自动生成默认拷贝构造函数,默认拷贝构造函数即位拷贝,又称浅拷贝
	深拷贝:复制过程中资源重新分配
	浅拷贝:资源不重新分配
	----浅拷贝的风险:进行复制过程中,两个对象指向同块内存,当析构函数释放内存时,会引起错误
	*/

	//c_Example A(100);		//对象实例化方式1
	//c_Example B = A;
	c_Example *A = new c_Example(100);//对象实例化方式2
	c_Example B = *A;
	B.show();

	{//使C、D成为局部变量,变量消除时才会调用析构函数
		deep_Example C(20, "hello");
		deep_Example D = C;//深拷贝,此处已执行两次析构函数
		D.show();
	}
	system("pause");
	return 0;
}

其他

1、构造函数后面的单冒号
eg. c_Example():_os(os)起到赋值作用,将os的值赋给_os,比较适合于const变量成员
2、内联函数:因为函数的调用需要进行创建、传参等,造成时间的额外开销,使用内联函数提高效率,但是相应的指令会增多,函数体积变大
eg.

#include<iostream>
using namespace std;
inline int Max(int a,int b){   //定义内联函数
    if(a>b) return a;
    else return b;
}
int main(){
    int a = 3;
    int b = 5;
    cout << "Max:" << Max(a,b) << endl;  //内联函数的定义
}

运行时实际的效果为:

#include<iostream>
using namespace std;
int main(){
    int a = 3;
    int b = 5;
    int temp;
    if(a>b) temp = a;
    else temp = b;
    cout << "MAX:" << temp << endl;;
}

猜你喜欢

转载自blog.csdn.net/qq_37708045/article/details/89046369
今日推荐