Returned objects life-time

R

Raider

What is returned objects life-time?
For example, is it safe:

#include <...>

std::string foo()
{
return std::string("foo");
}

std::string bar()
{
std::string bar("bar");
return bar;
}

void test(char* a, char* b)
{
....
}

int main()
{
test(foo().c_str(), bar().c_str());
}

Here I think might be a problem. foo() returns std::string objects,
c_str() returns some pointer into the std::string("foo") and passes
this pointer to the test(). But will std::string("foo") exist when
test() is executed?
 
V

Victor Bazarov

Raider said:
What is returned objects life-time?

Since it's a temporary, refer to "the life time of a temporary"
in your favourite C++ book. Hint: any temporary *usually* lives
until the full expression where it's created is evaluated, except
when it lives longer if bound to a reference to const.
For example, is it safe:

#include <...>

std::string foo()
{
return std::string("foo");
}

std::string bar()
{
std::string bar("bar");
return bar;
}

void test(char* a, char* b)
{
...
}

int main()
{
test(foo().c_str(), bar().c_str());

That shouldn't compile. Your 'test' needs pointers to non-const char
and 'c_str' returns a pointer to const char.
}

Here I think might be a problem. foo() returns std::string objects,
c_str() returns some pointer into the std::string("foo") and passes
this pointer to the test(). But will std::string("foo") exist when
test() is executed?

From the lifetime point of view, yes. You still need to make your
code const-correct.

V
 

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

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top