C++指針的指針和指針的引用

分析以下代碼:ios

#include <iostream>

using namespace std;

//指針
void func1(int *ptr)
{
    ptr = new int(10);
}

//指針的指針
void func2(int **ptr)
{
    *ptr = new int(20);
}

//指針的引用
void func3(int *&ptr)
{
    ptr = new int(30);
}

int main(int argc, char *argv[])
{
    int val1 = 5;
    int val2 = 5;
    int val3 = 5;
    int* ptr1 = &val1;
    int* ptr2 = &val2;
    int* ptr3 = &val3;
    cout << *ptr1 << endl;
    cout << *ptr2 << endl;
    cout << *ptr3 << endl;
    cout << endl;

    func1(ptr1);
    func2(&ptr2);
    func3(ptr3);
    cout << *ptr1 << endl;
    cout << *ptr2 << endl;
    cout << *ptr3 << endl;

    return 0;
}

輸出結果:函數

Debugging starts
5
5
5

5
20
30
Debugging has finished

第一種狀況下咱們是沒法獲取到新分配的內存數據,並且還會致使內存泄漏,最後ptr1的內容並未改變;spa

第二種和第三種狀況下均可以獲取到新分配的內存數據,不一樣之處在於第二種func2()中*ptr是一個指針,而在第三種狀況下,*ptr是一個指針的引用。他們的區別能夠參考指針和引用的區別來看待。在函數調用上也有所不一樣,func2(&ptr2)和func3(ptr3),這個時候func2(nullptr)是被編譯容許的,而func3(nullptr)就會編譯報錯:invalid initialization of non-const reference of type 'int*&' from an rvalue of type 'int*'
     func3(nullptr);,所以在咱們須要傳遞的參數不能爲nullptr時採用第三種方法較好。
                  ^指針

相關文章
相關標籤/搜索