Does assigning return value from a lambda cause a copy?

Viewed 74

I have used this pattern before to do module-specific initialization, e.g. at the top of a .cpp file:

static bool isInitialized = []()
{
    ...//do stuff
    return true;
}();

But what about something like:

static MyObject something = []()
{
    MyObject ret(...);
    ret.x(...)
    return ret;
}();

Is it definitive if something will be ret, or will be a copy? I want to avoid copying.

I'm working with VS2017/C++14 mainly, though moving to C++17 soon.

1 Answers

Case one should not be a copy in C++17. You are returning a prvalue, so no temporary is created and instead isInitialized is directly constructed. In C++14 this is only an optional optimization.

Case two is using a named variable so you would have to rely on NRVO, which is not guaranteed in any version of C++, to do that optimization. On the "plus" side, function local arguments are treated as rvalues in a return statement so ret will be moved if it can, and only copied if it can't.

Related