Search code examples
c++visual-studioreturn-value-optimization

How to activate (N)RVO for aggregates in Visual Studio?


Is it true that Visual C++ supports (named) return value optimization (N)RVO for aggregates?

In the example as follows:

struct Vector
{
    float data[100];
};

void print(const Vector & v);

inline Vector makeVector()
{
    Vector c;
    return c;
}

void foo()
{
    print(makeVector());
}

compiled with optimization (/O2 switch) https://godbolt.org/g/bb8HZj one can easily see that there is copying of the Vector constructed in makeVector() function

    lea      rcx, QWORD PTR [rcx+128]
    movups   xmm0, XMMWORD PTR [rax]
    lea      rax, QWORD PTR [rax+128]
    movups   XMMWORD PTR [rcx-128], xmm0
    movups   xmm1, XMMWORD PTR [rax-112]
    movups   XMMWORD PTR [rcx-112], xmm1
    movups   xmm0, XMMWORD PTR [rax-96]
    movups   XMMWORD PTR [rcx-96], xmm0
    ...

So it is clear that there is no NRVO here as in other compilers. Is there a way to turn on or activate it in Visual C++?


Solution

  • Looks like MSVC does not apply RVO to types that are seen as C structures. The solution is to make your Vector look like a C++ type (make it non-POD, but I am not sure if POD is what MSVC uses here). Try this:

    struct Vector
    {
        Vector() { }
    
        float data[100];
    };
    

    Careful, as it changes semantics: you won't be able to zero-initialize it with Vector v{}.