Date: Thu, 24 Apr 2025 04:09:26 +0300
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.
The full proposal is available here:
https://gist.github.com/elazarg/ffe096f8e5c237d60a5d6f5205f50e2e
What do you think? Are there specific use cases you'd like to see
addressed? Any implementation concerns?
Looking forward to your thoughts!
Best regards,
Elazar Gershuni
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.
The full proposal is available here:
https://gist.github.com/elazarg/ffe096f8e5c237d60a5d6f5205f50e2e
What do you think? Are there specific use cases you'd like to see
addressed? Any implementation concerns?
Looking forward to your thoughts!
Best regards,
Elazar Gershuni
Received on 2025-04-24 01:09:39