Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will C++ compiler optimize return-by-value code?

Tags:

c++

rvo

Lets assume i use Visual Studio or modern GCC with -O2. Will compiler create S inside func() and then copy it to a my_result, or will it create my_result with constructor (5, 6, 5 + 6) without creating temporary S?

NOTE: Function func() definition and its usage are in separate .obj files!

struct S
{
    S(int _x, int _y, int _z) : x(_x), y(_y), z(_z) { }
    int x, y, z;
};

S func(int a, int b)
{
    return S(a, b, a + b);
}


/// USAGE ///

S my_result = func( 5, 6 );
like image 958
pavelkolodin Avatar asked Dec 20 '22 00:12

pavelkolodin


1 Answers

Modern compilers will often optimize this kind of operation. See return value optimization

like image 118
jhauris Avatar answered Jan 06 '23 17:01

jhauris