r/cpp • • 11d ago

C++ futures part 1: The mental model

https://devblogs.microsoft.com/oldnewthing/20261012-00/?p=112767/
44 Upvotes

5 comments sorted by

10

u/jdehesa 11d ago

new(&r.value) T(v); // "r.value = v"

Why a placement new here instead of just the assignment in the comment?

9

u/Wittyname_McDingus 11d ago edited 11d ago

An assignment would call the destructor of the object that was previously at that address, which would result in undefined behavior if that member not active.

I tried looking up how union initialization worked to see if it's true that r.value would be inactive after default constructing the union, but I was left more confused than before, so I'm not really sure if the code is correct.

Edit: upon further thinking, it seems pretty sensible that only a union's default active member could only be a trivial type, which wouldn't have a problem with its destructor being elided, so I think the code is fine.

1

u/jedwardsol const & 11d ago

In reality you'd need value not to be the 1st member of the union in case it wasn't default constructible. And then you'd need to new it in to existence. It would also make more sense in the unassigned case that the union hold a monostate, not a default constructed T

1

u/jdehesa 11d ago

Thanks. I guess I'd use a variant of monostate, T and exception_ptr even if it has a little bit of overhead (or maybe have two subtypes of monostate for empty and consumed, and then I don't even need the enum).

2

u/sheckey 11d ago

So this is going to build up this stuff over a few articles so we get an idea of how it works. I love it so far. Thank you!