C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Idea: moved_from<T>() for Efficient Moved-From State Construction

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 23 Apr 2025 21:14:51 -0400
On Wed, Apr 23, 2025 at 9:09 PM Elazar via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hey everyone,
>
> I've been working on a new proposal for the C++ Standard Library that I'd like to share: "A Library-Based Mechanism for Moved-From Initialization (moved_from())"
>
> Problem: Creating an object just to immediately overwrite it, like:
>
> BigExpensiveType obj; // Default construction we don't need
> obj = get_actual_value(); // Immediate overwrite
>
> This is especially wasteful for types with non-trivial constructors. Current workarounds like placement new or custom factory functions are either unsafe or non-standard.
>
> Proposal: Add a standardized moved_from<T>() function that constructs objects directly in a moved-from state. Type authors opt-in by implementing T::moved_from().
>
> BigExpensiveType obj = moved_from<BigExpensiveType>();
> obj = get_actual_value(); // Now we're just overwriting a moved-from state
>
> This shifts implementation responsibility from client code to the type author (who knows the most about safely initializing their type), while providing stronger guarantees for compiler optimizations.

If a default constructor does more work than this "moved from"
constructor, wouldn't it make more sense to just... fix the default
constructor?

Many `std::list` implementations need to have an allocated node to
function. So the default constructor creates one. But the move
constructor *also* allocates one for the moved-from object, since
moved-from objects have to still be valid (this is also why
`std::list`'s move constructor is not required to be noexcept). So
it's unclear when exactly this would be advantageous.

Also, in what circumstances do you need to allocate an object, not
meaningfully touch it, but then copy-assign to it from another
instance of that type?

Received on 2025-04-24 01:15:04