默认复制构造函数 执行 浅拷贝
本文地址: 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