How many times value is copied when we return object by value?

Viewed 77

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?

1 Answers

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.

Related