But C++ has the return value optimisation (even the named return value optimisation), where you construct an object in a function and then "return" it, but it's actually constructed in place at the call site (not guaranteed but allowed by the language and widely implemented):
Foo make_foo() {
Foo result;
result.blah = 7;
return result;
}
Foo f = make_foo();
// Equivalent to:
Foo f;
f.blah = 7;
I don't know enough about Rust to know whether it has the same thing, but surely it could? If anything, it feels like it ought to be easier (for the compiler) because Rust moves rather than copies by default, and moves are destructive and bytewise.Given that, it seems like a language could be designed so that a static method that returns an object could be allowed to construct an object in place. Again, I don't know enough about Rust or Zig to know if that's true of them.
> not guaranteed but allowed by the language and widely implemented
Ome can make it guaranteed (assuming Foo is an aggregate) by writing:
Foo make_foo() {
return Foo{.blah = 7};
}
This guarantees initialization happens at the end of the function, since you are returning a pure rvalue. Generally a good style rule to adopt and no annotations needed.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?!
Rust doesn't really have a good answer for guaranteed copy elision or in-place initialization at the moment. The devs are working on it, though (https://github.com/rust-lang/rust/issues/153825).