淺談返回函數(shù)內(nèi)部new分配的內(nèi)存的引用
在bbs看到了一個(gè)帖子:為什么不能返回函數(shù)內(nèi)部new分配的內(nèi)存的引用?
lz是這樣問的:
按照這句話,
string& foo() { string* str = new string("abc"); return *str; }
非法的,為什么?
其實(shí),不能說這是非法的,只能說這種u編程習(xí)慣很不好,這樣很可能造成內(nèi)存泄露。
后面還有個(gè)回復(fù)是這樣的:
struct a_s { int a; }; a_s* foo() { struct a_s* sp = new struct a_s; return sp; }
這個(gè)挺好啊,為什么換成reference就泄漏了?
不能說這樣寫就挺好,這樣寫跟lz寫的都是一個(gè)道理,也并不是說這樣寫就內(nèi)存泄露了,只是說,這樣寫很容易造成內(nèi)存泄露。程序員在編寫代碼時(shí),為了避免內(nèi)存泄露,必須保證對(duì)每個(gè)用new產(chǎn)生的指針調(diào)用delete釋放。
如果按照以上兩種做法,即使很小心的程序員也難免會(huì)造成內(nèi)存泄露。
比如:string str = foo(); 顯然new生成的這塊內(nèi)存將無法釋放。
只能這樣:
string& tmp = foo(); string str = tmp; delete &tmp;
這樣就不會(huì)造成內(nèi)存泄露了。 但是每次的這樣就是誰都覺得煩。而且暗藏殺機(jī)啊,比如:string str = "hello" + foo(); 上式不知不覺就造成內(nèi)存泄露了。所以,即使很小心的程序員也難免會(huì)造成內(nèi)存泄露。
為了證明我的思想,我寫了測(cè)試代碼:(vs2008調(diào)式通過)
#include <iostream> using namespace std; class example { public: example() { num = new int; *num = 10; cout<<"num = "<<*num<<endl; cout<<"構(gòu)造"<<endl; } ~example() { cout<<"析構(gòu)"<<endl; delete num; } void pingfang() { *num *= *num; } void print() { cout<<*num<<endl; } private: int *num; }; example & diaoyong1() { example * p = new example; p->pingfang(); return *p; } example * diaoyong2() { example * p = new example; p->pingfang(); return p; } int main(void) { example & e1 = diaoyong1(); e1.print(); delete &e1; example * ptr = diaoyong2(); ptr->print(); delete ptr; getchar(); return 0; }
運(yùn)行結(jié)果如下:
num = 10
構(gòu)造
100
析構(gòu)
num = 10
構(gòu)造
100
析構(gòu)
從運(yùn)行結(jié)果來看:我的結(jié)論如下:
并不是說返回函數(shù)內(nèi)存new分配的內(nèi)存的引用或指針是非法的,只是說如果要返回,必須要十分注意,因?yàn)楹苡锌赡茉斐蓛?nèi)存泄露。所以一般不提倡返回函數(shù)內(nèi)存new分配的內(nèi)存的引用或指針。
以上就是小編為大家?guī)淼臏\談返回函數(shù)內(nèi)部new分配的內(nèi)存的引用全部?jī)?nèi)容了,希望大家多多支持腳本之家~
相關(guān)文章

stl容器set,map,vector之erase用法與返回值詳細(xì)解析

C++11?lambda(匿名函數(shù))表達(dá)式詳細(xì)介紹