Why is returning a reference to a string literal a reference to a temporary?
Asked Answered
L

3

11

A regular string string literal has the following definition:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

I'm assuming because it has static storage duration and that they're typically placed in ROM, it really isn't a big deal if there's a dangling reference to it. The following code emits a warning

const char* const & foo()
{
    return "Hello";
}
// warning: returning reference to temporary [-Wreturn-local-addr]

But this is fine, even without the static keyword

const char* const & foo()
{
    const char* const & s = "Hello";
    return s;
}

So what is the difference between the two?

Levigate answered 26/3, 2015 at 12:23 Comment(3)
Your code isn't returning a reference to a string literal. It's returning a reference to a pointer. Most of what you cite is irrelevant to the code.Warren
Where is your cite from? You should add it.Krystinakrystle
Why are you returning a reference to a char-pointer instead of the char-pointer itself?Jameyjami
H
10

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.

Howlend answered 26/3, 2015 at 12:29 Comment(0)
M
8

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.

Mesenchyme answered 26/3, 2015 at 12:26 Comment(0)
M
2
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.

Mohun answered 26/3, 2015 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.