Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is the ignored return value destruction behavior well-defined

Tags:

Question: Is an ignored return value destructed immediately or at the moment going out of scope.?

The code below returns for my compiler

Output:

Who makes it, has no need of it.

Who buys it, has no use for it.

Who uses it can neither see nor feel it.

What is it?

Therefore the ignored value is destructed immediatly. But is this compiler specific or standard-behavior?

struct foo
{
   ~foo()
   {
      std::cout << "Who makes it, has no need of it. \n"
                << "Who buys it, has no use for it. \n";
   }
}

foo createFoo()
{
   return foo();
}

int main(int argc, char* argv[])
{
     createFoo();
     std::cout << "Who uses it can neither see nor feel it.\n"
               << "What is it?"; 
}
like image 759
user1235183 Avatar asked May 19 '15 15:05

user1235183


1 Answers

The returned temporary is destroyed immediately after the full expression completes except if its lifetime is extended by being bound to an rvalue or const lvalue reference.

like image 59
Mark B Avatar answered Oct 21 '22 16:10

Mark B