return a local std::string

J

Jun Yan

Hi all,

I am seeing this kind of code,

std::strnig foo()
{
std::string ret = "bla bla";
return ret;
}

Just curious, what will happen, when call foo?

thanks,


Jun
 
G

Gert-Jan de Vos

Hi all,

I am seeing this kind of code,

std::strnig foo()
{
    std::string ret = "bla bla";
    return ret;
}

Just curious, what will happen, when call foo?

It should not compile since there is no "strnig" in the std
namespace..

Seriously: The caller of foo() gets a copy of the local string ret,
same contents. This is fine as you are returning the string object by
value. If you would try to return it by reference, then you would get
problems. A reference to a local object of a function is no longer
valid after the function returns. A copy of its value is. Clear?
 
P

peter koch

Hi all,

I am seeing this kind of code,

std::strnig foo()
{
    std::string ret = "bla bla";
    return ret;

}

Just curious, what will happen, when call foo?

It will return a string for you to use; whether the string is copied
or not is implementation-defined. In your example, I am quite
confident that no copy will take place, provided you ask the compiler
to optimize just a little.

/Peter
 

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
474,156
Messages
2,570,878
Members
47,408
Latest member
AlenaRay88

Latest Threads

Top