关于用函数指针参数申请动态内存的问题
生活随笔
收集整理的這篇文章主要介紹了
关于用函数指针参数申请动态内存的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天在寫一個Binary Search Tree的程序時,發現其插入有問題,下面是插入程序,每次插入完成后,節點還是NULL。
template<typename Object>
void CMyTree<Object>::insert(const Object& element, BinaryNode<Object>* node)
{if(node == NULL)node = new BinaryNode<Object>(element); //新建節點,插入else if(element < node->element)insert(element, node->left); //從左邊遞歸else if(node->element < element)insert(element, node->right); //從右邊遞歸
}??????? 仔細檢查后發現了問題的所在,我使用了函數指針參數來申請動態內存。突然想起在《高質量C/C++編程》一書中,作者曾提出了“
如果函數的參數是一個指針,不要指望用該指針去申請動態內存”,而我正犯了這個錯誤。下面將結合該書對此問題做深入分析,以此記錄,避免以后再犯錯。
int* func() {int* t = new int;return t; } int main() {int* test =func();delete test;system("pause");return 0; }
?????? 我們將上述問題抽象出來,如下代碼:
#include <iostream> using namespace std; void func(int* t) {t = new int; } int main() {int* test =NULL;func(test);delete test;system("pause");return 0; }??????? 首先來分析下指針參數傳遞的原理。編譯器總是要給每個函數參數創建一個臨時副本,例如指針參數m的臨時副本是_m,_m=m,此時_m和m指向同一段內存地址,如圖1所示。因此,當我們修改地址1的內容時,實際也就修改了m所指向的內存的內容,這一點與我們平時使用指針參數的目的是一致的。然而,當我們修改_m的值(為其申請動態內存)時,只是將_m指向另一段內存地址(地址2),而m仍然指向地址1,這就相當于值傳遞了,是無法更改變量內容的。同時,這么做的話為造成內存泄露。
??? 如果需要通過指針參數來申請動態內存,有三種做法:
(1)使用指向指針的指針參數,即func(int** t)
void func(int** t) {*t = new int; } <pre class="cpp" name="code">int main() {int* test =NULL;func(&test);delete test;system("pause");return 0; } (2)使用指針的引用,即func( int*& t) void func(int* &t) {t = new int; } int main() {int* test =NULL;func(test);delete test;system("pause");return 0; } (3)使用函數返回值來傳遞動態內存,即 int* func()int* func() {int* t = new int;return t; } int main() {int* test =func();delete test;system("pause");return 0; }
?
?
總結
以上是生活随笔為你收集整理的关于用函数指针参数申请动态内存的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android之内存机制分析-Andro
- 下一篇: java.lang.IllegalSta