Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are destructors not meant to be called when returning that object (not as a pointer)?

Tags:

c++

destructor

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?

like image 364
kamziro Avatar asked Dec 29 '22 01:12

kamziro


1 Answers

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.

like image 164
ergosys Avatar answered Jan 25 '23 15:01

ergosys