1

Is the concept of "Return Value Optimization" applied for lambda expression in C++ Compilers? I know that it depends on the compiler and the optimization parameters but is it theoretical possible?

BTW, does anyone know about this issue in VS.NET 2013 or higher?

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160

2 Answers2

4

Yes, it is possible. You can prove it with a little example.

The following code produced this output, when I compiled with clang and g++ with the -O2 option:

Ctor

So, "copy" was not printed. This means that NO copy happened.

#include <iostream>

class Test
{
public:
    Test() { std::cout << "Ctor\n";}
    Test(const Test& t) 
    {
        std::cout << "copy" << std::endl;
    }
};

int main()
{    
    auto myLambda = []() 
    {
        return Test();
    };

    Test t = myLambda(); 
}

RVO applies to the return value of a function. A lambda is compiled as a functor. So, it still is a function.

As for why does it not work in VS, maybe this post can help you.

Community
  • 1
  • 1
Pumkko
  • 1,523
  • 15
  • 19
  • sorry I did not get you... how did you exactly make sure by this example that it is applied? – Humam Helfawi Oct 19 '15 at 11:02
  • The copy constructor is not called only the constructor. So a copy was not made. – Pumkko Oct 19 '15 at 11:03
  • 1
    To be meaningful, such code should probably do something with `t` so that the entire program isn't just optimised away to nothing. It _wasn't_ in my case with `g++`, and nor did adding a member `int a{4}` and `cout << t.a` make any difference, so I can confirm your results... but still, when we're measuring optimisations, we should always take steps to make sure _other_ optimisations don't make our measurements meaningless! ;-) – underscore_d Jul 03 '16 at 00:01
0

but is it theoretical possible?

I don't see any reason why not. lamda's are on-the-fly compile time generated structs with () operator overloaded.

meaning that this :

auto f = []{printf("hi");};

will probably be translated to

struct lambda<someID>{  void operator(){printf("hi");}  };
auto f = lambda<someID>();

so, there is no reason why RVO wouldn't work here if the compiler thinks it may optimize things up.

David Haim
  • 25,446
  • 3
  • 44
  • 78