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?
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.