簡體   English   中英

使用函數將引用變量初始化為指針

[英]initializing reference variable to a pointer using a function

為什么我不能通過函數使用預定義的指針變量來初始化引用變量?

int * f(int * p) {
    return p;
}

int main(){
    int  s=10;
    int *p=&s;
    int *&ref1 = p;    //no error given here
    int *&ref2 = f(p); //gives error cannot initialize int * & with int * why??
}

您將在此處按值返回指針:

int* f(int* p)
^^^^

它是副本,是臨時的,這意味着您無法保存對其的引用。

這是行不通的,因為您嘗試引用f(p)返回的指針,這是一個臨時變量,在表達式的末尾超出范圍。 您將創建一個懸空引用,並且編譯器阻止您這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM