Shouldn't destructors be called when this object returns (and not as a pointer)?

I have a function:

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

And the main function:

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

The destructor in Bwah is called only once, after printing "received here". Is this a guarantee or is it a compiler optimization?

+4
source share
1 answer

This is an optimization called Return Value Optimization (RVO). This is a normal optimization, but you cannot rely on it.

Here are two really great links for learning more:

The Wikipedia article, in particular, directly relates to your question. But in another article, the whole question is considered in more detail.

+10
source

Source: https://habr.com/ru/post/1301936/


All Articles