C++ - 默认复制构造函数 执行 浅拷贝

默认复制构造函数 执行 浅拷贝

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/23941807

 

C++, 会默认生成一个复制构造函数, 当类中出现指针时, 复制会执行浅拷贝, 即只复制指针的地址, 不会复制数据;

所以在类中, 使用指针时, 需要注意; 如果想使用深拷贝, 可以添加复制构造函数.

 

以下代码, 如果不添加复制构造函数, 则会运行出错, 但可以通过编译

运行时, 因为删除(delete[])两次str所指的同一片地址空间, 所以程序无法执行.

 

代码:

 

/*
 * main.cpp
 *
 *  Created on: 2014.4.15
 *      Author: Spike
 */

/*vs2012*/

#include <iostream>
#include <cstring>
#include <vector>
#include <memory>

using namespace std;

class CDemo {
public:
	CDemo() : str(NULL) {};
	~CDemo() {
		static int i=0;
		if (str) {
			std::cout << "&Demo" << i++ << " = " << (int*)this << ", str = " << (int*)str << std::endl;
			delete[] str;
		}
	}

	//复制构造函数
	CDemo(const CDemo& cd) {
		this->str = new char[strlen(cd.str) + 1];
		strcpy(this->str, cd.str);
	}

	char* str;
};

int main () {
	CDemo d1;
	d1.str = new char[32];
	strcpy(d1.str, "Caroline");
	std::vector<CDemo>* a1 = new std::vector<CDemo>();
	a1->push_back(d1); //执行复制构造函数
	std::cout << "d1.str = " << d1.str << std::endl;
	std::cout << "(*a1)[0].str  = " << (*a1)[0].str << std::endl;
	strcpy(d1.str, "Wendy");
	std::cout << "d1.str = " << d1.str << std::endl;
	std::cout << "(*a1)[0].str  = " << (*a1)[0].str << std::endl;
	delete a1;
	return 0;
}


输出:

 

 

d1.str = Caroline
(*a1)[0].str  = Caroline
d1.str = Wendy
(*a1)[0].str  = Wendy
&Demo0 = 0x312570, str = 0x312548
&Demo1 = 0x22fec8, str = 0x312548

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值