tags:

views:

108

answers:

1

I have a function:

static Bwah boo(){
   Bwah bwah;
   return bwah;
}

And a main function:

int main(){
   Bwah boo = Assigner::boo();
   cout << "got here.." << endl;
}

The destructor to Bwah is only called once, after the "got here" print. Is this guaranteed or is this a compiler optimization?

+7  A: 

This is an optimization called Return Value Optimization (RVO). It is a common optimization, but you can't rely on it.

Here are two really excellent links for learning more:

  1. First, a really detailed article about pass by value, rvalue semantics, the return value optimization, and rvalue references and the move constructor and assignment operator in C++0x
  2. Second, the good old standby Wikipedia and their entry on the return value optimization.

The Wikipedia article in particular directly addresses your question. But the other article goes more in depth about the whole issue.

ergosys
A link might be nice. :-)
Omnifarious
More info on it if you don't wanna google it:http://en.wikipedia.org/wiki/Return_value_optimization
SB
Good article on this and related topics: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
ergosys
I'm editing these links into your answer. Feel free to back out my change.
Omnifarious
@Omnifarious, thanks much.
ergosys
Thanks guys, really informative :)
kamziro