[optional] swapping initialized with uninitialized

Hi, When two optionals (one initialized and other not) are swaped, then the one value in uninitialized optional is constructed and the other one in initialized optional is destructed. IMHO it's not necessary. It should be more effective to swap optional's m_storages without any values constructiona and destruction. Is there any reason for the current implementation? Regards, Vaclav

"Vaclav Vesely" <vaclav.vesely@email.cz> wrote in message news:002101c6445d$ad1723e0$a6cddcd5@nbvasek...
Hi,
When two optionals (one initialized and other not) are swaped, then the one value in uninitialized optional is constructed and the other one in initialized optional is destructed.
IMHO it's not necessary. It should be more effective to swap optional's m_storages without any values constructiona and destruction.
Is there any reason for the current implementation?
It would be easy to swap two optionals like this if optional<T> were implemented using pointers to T that were constructed using new and destructed using delete, but optional is not implemented this way. It is implemented using char buffers, with in-place constructors and destructors used to construct and destruct. There are plusses and minuses to both approaches. One advantage of the current approach is that construction and destruction are much faster because they don't have to call new and delete, but a disadvantage is that there is no easy way to swap two optionals when one is initialized and the other isn't. Joe Gottman

On Friday 10 March 2006 17:14, Vaclav Vesely wrote:
When two optionals (one initialized and other not) are swaped, then the one value in uninitialized optional is constructed and the other one in initialized optional is destructed.
IMHO it's not necessary. It should be more effective to swap optional's m_storages without any values constructiona and destruction.
Is there any reason for the current implementation?
You can't simply do so. The reason is that an object might contain (directly or indirectly) a pointer to itself. Now, if you'd just swap memory bytewise, it would change its address but those pointers would not be updated. It could only be done if the object was moveable, i.e. depending on a type_trait. Looking at the Boost type_traits library, I wonder why this trait doesn't exist - many things can be sped up using memcpy when is_pod is true, but even things like vector/string/deque (list/map/set depending on whether their root node is stored by pointer) can be moved in memory without negative effects (yes, talking about typical implementations here, not guarantees). Uli
participants (3)
-
Joe Gottman
-
Ulrich Eckhardt
-
Vaclav Vesely