cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

comment on ep205 lambda as a way to take benefit of (N)RVO

Open Dharmesh946 opened this issue 1 year ago • 1 comments

Sorry I didn't find the ep205 corresponding "issue".

In this episode and in some previous one on lambda. It is claimed that lambdas can be used to optimize some variable creation. The canonical example given is

#include <vector>

void f() {
    const auto value = []() {
        std::vector<int> vec(10, 10);
        vec.push_back(42);
        return vec;
    }();
}

Yet

#include <vector>

void g() {
    std::vector<int> vec(10, 10);
    vec.push_back(42);
    const auto value = std::move(vec);
}

seems to lead to the exact same assembly : https://godbolt.org/z/bc6TxY7vW. This more verbose snippet, shows also that NRVO might fail inside the lambda (which are submitted to the same rules as regular functions) : https://godbolt.org/z/hG1qT18K1

Would it be possible to have a clarification?

Dharmesh946 avatar Nov 18 '24 14:11 Dharmesh946

from https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-lambda-init I guess that it comes useful in case of not movable intermediate object?

Dharmesh946 avatar Nov 19 '24 09:11 Dharmesh946