C++編程小心指針被delete兩次
在C++類中,有時候會使用到傳值調(diào)用(即使用對象實(shí)體做參數(shù)),當(dāng)遇到這種情況,可要小心了!尤其是當(dāng)你所傳值的對象生命周期較長,而非臨時對象(生命周期段)的時候。來看看下面的情況:
#include <iostream> using namespace std; class Text { private: char * str; public: Text(){str = new char[20]; ::memset(str,0,20); } void SetText(char * str) { strcpy(this->str,str); } char * GetText() const{return str;} ~Text() { cout << "~Text Destruction" << endl; delete [] str; cout << "~Text Over" << endl; } }; void Print(Text str) { cout << str.GetText() << endl; } int main() { Text t; t.SetText("abc"); Print(t); return 1; }
上面執(zhí)行的結(jié)果是程序崩潰了。原因是:
Print(Text str)在對str進(jìn)行復(fù)制構(gòu)造的時候,沒有進(jìn)行深度拷貝;當(dāng) Print退出的時候,因?yàn)槭桥R時對象(函數(shù)初始時構(gòu)造),對str進(jìn)行析構(gòu),此時還沒有出現(xiàn)任何問題;但回到main,繼而退出main 的時候,又對t進(jìn)行析構(gòu),但此時t內(nèi)的str中的內(nèi)容已經(jīng)被銷毀。由于對一內(nèi)存空間實(shí)施了兩次銷毀,于是就出現(xiàn)了內(nèi)存出錯。
解決方法如下:
重寫前拷貝。像以下版本,不同的情況要作出適當(dāng)?shù)恼{(diào)整:
#include <iostream> using namespace std; class Text { private: char * str; public: Text(){str = new char[20];::memset(str,0,20);} Text(Text &t) { str = new char[20]; strcpy(str,t.GetText()); } void SetText(char * str) { strcpy(this->str,str); } char * GetText() const{return str;} ~Text() { cout << "~Text Destruction" << endl; delete [] str; cout << "~Text Over" << endl; } }; void Print(Text str) { cout << str.GetText() << endl; } int main() { Text t; t.SetText("abc"); Print(t); return 1; }
此處推薦不使用傳值調(diào)用。就像下面書寫如下Print版本:
void Print(Text &str) { cout << str.GetText() << endl; }
除非對象內(nèi)所有的成員讀屬非指針內(nèi)存內(nèi)容,那么謹(jǐn)慎使用文章前面提到的用法。
相關(guān)文章
C語言數(shù)據(jù)結(jié)構(gòu)不掛科指南之棧&隊列&數(shù)組詳解
自考重點(diǎn)、期末考試必過指南,這篇文章讓你理解什么是棧、什么是隊列、什么是數(shù)組。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-09-09c++項(xiàng)目中后綴名vcxproj和sln的區(qū)別及說明
這篇文章主要介紹了c++項(xiàng)目中后綴名vcxproj和sln的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05全面解析C++中的new,operator new與placement new
以下是C++中的new,operator new與placement new進(jìn)行了詳細(xì)的說明介紹,需要的朋友可以過來參考下2013-09-09VC++實(shí)現(xiàn)的OpenGL線性漸變色繪制操作示例
這篇文章主要介紹了VC++實(shí)現(xiàn)的OpenGL線性漸變色繪制操作,結(jié)合實(shí)例形式分析了VC++基于OpenGL進(jìn)行圖形繪制的相關(guān)操作技巧,需要的朋友可以參考下2017-07-07C語言靜態(tài)版通訊錄的設(shè)計與實(shí)現(xiàn)
靜態(tài)版通訊錄是一種簡單的通訊錄實(shí)現(xiàn)方式,通過定義固定的數(shù)組大小來存儲聯(lián)系人信息。該方法不支持動態(tài)增刪聯(lián)系人,但具有實(shí)現(xiàn)簡單、易于理解的優(yōu)點(diǎn)。在程序設(shè)計中,需注意數(shù)組邊界溢出等問題2023-04-04