einpoklum
einpoklum

Reputation: 132240

How come I can capture an object being constructed in the lambda doing the construction?

Consider the following code:

int x = [&x](){
    std::cout << "Inside lambda, x is " << x << '\n';
    x = 5;
    return 23;
}();
std::cout << "x is " << x << '\n';

This compiles and runs! And without any warnings, too! I'm actually a bit shocked. What's going on here? How am I allowed to capture an unconstructed object and read and write from it?

And if you think "This is fine, since int is default-constructible, so probably x gets default constructed" - then try this:

struct Int {
    int v;
    Int(int v):v{v}{}
};

static_assert(!std::is_constructible_v<Int>);
static_assert(std::is_constructible_v<Int, int>);

int main()
{
    Int x = [&x](){
        std::cout << "Inside lambda, x is " << x.v << '\n';
        x = 5;
        return 23;
    }();
    std::cout << "x is " << x.v << '\n';
}

and that also compiles and runs.

Upvotes: 3

Views: 71

Answers (0)

Related Questions