Why is returning a reference to a string literal a reference to a temporary?

回眸只為那壹抹淺笑 提交于 2019-12-03 11:35:34

The quote you've posted says that

A narrow string literal has type “array of n const char”

That is, the type of "Hello" is const char[6].

Your code is returning a reference to a const char *. This means the array-to-pointer conversion must be applied to the string literal, resulting in a prvalue (= temporary) of type const char *. You then bind this to a reference and return that reference. The reference becomes dangling as soon as the function's scope ends and the temporary pointer is destroyed.

There is no difference. In both cases, you return a reference to a pointer that no longer exists.

That the pointee (data) still exists forever is irrelevant.

const char* const & s = "Hello";

Here the variable is created on the stack... and that variable (which happens to be a pointer) points to a memory location where the string-literal is stored. You're not returning the string-literal itself; you're rather returning the reference to the variable will be destroyed soon as a result of stack-unwinding. Hence the returning the reference to such a variable is dangerous, as it is a temporary object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!