Why is return value optimization happening here

206 views Asked by At

From this post it states

When a nameless temporary, not bound to any references, would be moved or copied into an object of the same cv-unqualified type, the copy/move is omitted. When that temporary is constructed, it is constructed directly in the storage where it would otherwise be moved or copied to. When the nameless temporary is the argument of a return statement, this variant of copy elision is known as RVO, "return value optimization".

So in order to test that concept i tried the following experiment

class C
{
    public:
        C()
        {
            std::cout << "Constructor of C." << std::endl;
        }
        C(const C &)
        {
            std::cout << "Copy-constructor of C." << std::endl;
        }
};

C func()
{
    const C c;
    return c; //c is not a nameless and is not CV unqualified as it is a const type. 
}

int main(int argc, char **argv)
{
    C c = func();
}

Output : Constrcutor of C

I was expecting: Constructor of C Copy-Constructor of C Copy-Constructor of C

My question is why is return value optimization happening here ?

1

There are 1 answers

2
Kerrek SB On BEST ANSWER

Because you've quoted an irrelevant paragraph. The relevant one is the one above (from the same source):

If a function returns a class type by value, and the return statement's expression is the name of a non-volatile object with automatic storage duration, which isn't the function parameter, or a catch clause parameter, and which has the same cv-unqualified type as the return type of the function, then copy/move is omitted.

Any of the stated conditions permit copy elision.