C++ Logo

std-proposals

Advanced search

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

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Thu, 24 Apr 2025 09:22:37 +0100
On Thu, 24 Apr 2025, 08:56 Andrey Semashev via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> On 24 Apr 2025 10:16, Jonathan Wakely via Std-Proposals wrote:
> >
> >
> > On Thu, 24 Apr 2025, 02:09 Elazar via Std-Proposals, <std-
> > proposals_at_[hidden] <mailto: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.
> >
> >
> > Use std::optional, that's safe and standard.
>
> And also larger and heavier than necessary.
>

Yes but it works today, without needing a language change.


> I often find std::optional a disappointment in practice. In objects with
> lots of std::optional members,


That isn't the situation that was given as motivation by the OP though. I
didn't say you should use optional in all situations.

it nearly doubles the object size due to
> padding, and I often find myself replacing it with separate T members
> and bools or even std::bitset. This is, of course, tedious and requires
> discipline on the user. It also needs T to be cheaply constructible,


Why? You would construct it with nullopt to avoid the default construction.


and
> could benefit from a proposal like this one.
>

I don't really see how.

Received on 2025-04-24 08:22:56