Remix.run Logo
▲ kpw94 4 hours ago

right, first-class support for a special say "must_construct_inplace" keyword on a function returning an object would be an interesting language design direction...

What happens inside

    must_construct_inplace Foo make_foo() { ... }
can be as "inefficient" as your example above, but the compiler would validate & figure out a way to make it an in-place-construction, guaranteed RVO.

(similar to `constexpr` validation)

EDIT: Looks like this already exists under several names ("build-in-place", "placement by return", "result location semantics") in Ada's `return W : Widget do ... end return;`, Carbon's returned var c: Circle; ... return var;`, and Rust has (still open) RFC 2884 "placement by return", and Zig seems to have this fully built-in via result location semantics?!

▲gpderetta an hour ago | parent [-]

RVO helps, but it is not necessarily enough. Let's say you have a vector and you want to construct in-place an element with an arbitrary set of arguments.

In c++ this is solved[1] via 1) emplace_back 2) perfect forwarding 3) constructors having an homogeneous name and being selected via overload resolution.

In a language with RVO, it is not enough for 'make_foo' in 'push_back(make_foo(args...))' to guarantee zero copy, 'push_back(x)' must also be able to guarantee that its parameter x is somehow constructed in place.

In practice you need some form of lazy evaluation (call by name, or an explicit thunk or passing the function and parameters separately) or some form of macro expansion.

[1] it does comes with its own set of foot-bazookas of course.