2

I want to know if my understanding of temporary objects and returning by value is correct. So consider next code:

int function()
{
    int value = 0;
    /*
    Some calculations
    */
    return value;
}

int main(int argc, char *argv[])
{
    int i = function();

    return 0;       
}

So when we call function in main does temporary object with scope of expression is created and value of return expression which resides in stack gets copied into it? So total number of copying in expression int i = function(); will be 2?

Aisec Nory
  • 385
  • 1
  • 8
  • 1
    I assume, you may be interested in this (old) [article](https://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/#fnref:saks). – rawrex Jul 07 '21 at 10:21

1 Answers1

1

It can be 0, 1 and 2, depending on compiler optimization capabilities and setting. See e.g. this answer:

What are copy elision and return value optimization?

One way how to be sure is to inspect the assembly created by your compiler. Another way is to use a single value class and add a print to all special member functions to see what is happening during the object lifetime.

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28