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
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/