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