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
作者:csdn博客 Spike_King