簡體   English   中英

從函數返回對指針的引用與返回指針相同?

[英]Returning a reference to a pointer from a function same as returning a pointer?

我感覺下面的兩個示例是等效的,也就是說,返回對指針的引用和返回指針是同一回事。 這么說聽起來很奇怪,對指針和指針的引用是同一回事,但我認為在此示例中就是這種情況:

#include <unordered_map>

struct Animal{};

std::unordered_map<std::string, Animal*> map;

Animal* createNewMapEntry()
{
    return map["new entry"] = new Animal; // map subscript operator will return a reference to the mapped type
                                        // in this case the mapped type is a pointer to Animal
    // Is this the equivalent of doing:
    auto p = new Animal;
    map["new entry"] = p;
    return p;
    // In this case I am returning a pointer to Animal, not a reference to the pointer to animal.
    // That's why I was afraid that in the first example, which returns a "reference" to the Animal pointer
    // that it was returning the "address" of the pointer instead of the pointer, equivalent to returning 
    // a pointer to pointer, which is just like the address to a pointer.
}

如果這是真的,我認為這是語言的一個真正令人困惑的部分,至少對我而言。

我覺得以下兩個示例是等效的。

,不是。

第一個插入到地圖中,鍵為“新條目”,並為Animal對象賦值。

第二個不執行此操作,因為它僅返回指針。


就像MM所說的:“如果一個函數按值返回並且您返回一個左值,則左值將轉換為prvalue,因此return語句僅返回指針”。

作為函數體的復合語句的內容對函數的返回類型沒有影響(除非返回類型為auto )。

返回類型是Animal* ,這不是引用類型。 這些示例在語義上是等效的。

的轉換T&T在表達式是C ++的一個基本方面。 這是在表達式求值過程中發生的第一件事。 參見[expr] / 5

如果表達式最初的類型為“對T引用”([dcl.ref],[dcl.init.ref]),則在進行任何進一步分析之前,將類型調整為T 表達式指定由引用表示的對象或功能,並且表達式取決於表達式是左值還是x值。

由於map["new entry"]Animal*& (並且賦值表達式返回一個引用左操作數左值 ),因此return表達式中的&消失,剩下一個左值 Animal* 之后,由於createNewMapEntry()的預期返回類型為Animal* ,因此將進行左值到右值轉換,並返回指針的副本

注意-返回類型始終是聲明的Animal* ,在此示例中,您永遠不要“ 返回引用 ”。 在兩種情況下都返回一個指針

暫無
暫無

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

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