Are string literals local or otherwise temporary?

K

Kza

This is probably just newbie silliness to all you c++ gurus but I just
noticed an interesting compiler warning today while compiling this
function:

const std::string& someclass::somemethod()
{
return "This is a string literal";
}

The compiler warned me that an address of a local variable or a
temporary value is being returned.

Does this make sense? Arent string literals basically static chunks of
memory in the data segment?

Why would this be created on the stack?

Or whats going on here and how can I be sure the string is always
available to the caller of the method?

Its no big drama, I am sure I could fix it, but I am just trying to
understand the language etc and how it all works behind the scenes.

Thanks a lot

Kurt
 
I

Ivan Vecerina

: This is probably just newbie silliness to all you c++ gurus but I just
: noticed an interesting compiler warning today while compiling this
: function:
:
: const std::string& someclass::somemethod()
: {
: return "This is a string literal";
: }
:
: The compiler warned me that an address of a local variable or a
: temporary value is being returned.
:
: Does this make sense? Arent string literals basically static chunks of
: memory in the data segment?
Yes. But note that string literals are of type (const) char[].

: Why would this be created on the stack?
: Or whats going on here and how can I be sure the string is always
: available to the caller of the method?
You are not returning an array of characters (or a char const*),
but an object of type std::string (a class defined in the standard
C++ library).
Therefore, your return statement involves an implicit conversion,
and is equivalent to:
return std::string("This is a string literal");
You are indeed returning a reference to the temporary std::string
object being created for the conversion.

: Its no big drama, I am sure I could fix it, but I am just trying to
: understand the language etc and how it all works behind the scenes.

I hope this helped,
Ivan
 
A

Alf P. Steinbach

* Kza:
This is probably just newbie silliness to all you c++ gurus but I just
noticed an interesting compiler warning today while compiling this
function:

const std::string& someclass::somemethod()
{
return "This is a string literal";
}

The compiler warned me that an address of a local variable or a
temporary value is being returned.

You're returning a reference to a temporary object.

Change the result type to

std::string

Nothing more.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,060
Latest member
BuyKetozenseACV

Latest Threads

Top