[英]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.