For ergonomics in the general case, I agree that it's not even a question, the Rust/Zig create-and-return approach wins on every count.
However, create-and-return makes in place construction difficult. C++ allows you to construct directly into any pinned memory block with satisfactory size and alignment, whereas create-and-return requires you to construct elsewhere and then copy the bytes. This has downstream implications:
- The address of "this" always changes at least once, which makes self-referential data structures and cyclic data structures more difficult. Now you have a pointer fixup step, or you are passing around some form of handle rather than raw pointers. These solutions can range from trivial to complicated, fast to slow, depending on the specific patterns in your code base. A simpler work around is to always construct with a fresh heap allocation and return a pointer to it, which, again, may or may not be an acceptably performant solution for your particular problem.
- You have to rely on your optimizer to do copy elision, which is not a guarantee. Not an issue for small objects, but it can become an issue for larger ones or for many repeated constructions.
> However, create-and-return makes in place construction difficult
This is definitely the closest thing to an answer in this thread. This is something that languages without constructors do struggle with, yes, and as other commenters pointed out, Rust sees this as a performance issue and is working on it.
Thanks for the informative reply.
Agree. C++17 lets you write factory functions that directly return `T(args...)` and can initialize an `auto foo = make_t();` so in many cases the distinction between rust and modern c++ is diminished.
But still, doing `std::make_unique<T>(args...)` or allocates storage and guarantees to run T's constructor there, and you can even do `std::optional<std::mutex> slot; slot.emplace();` which builds the mutex inside the optional even though a std mutex can't be moved or copied.
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):
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.