C++ Logo

std-discussion

Advanced search

Re: Standard guarantees on moved-from container

From: Anoop Rana <ranaanoop986_at_[hidden]>
Date: Wed, 10 Jul 2024 22:44:23 +0530
https://stackoverflow.com/q/17730689

On Sun, 7 Jul 2024, 03:53 Brian Bi via Std-Discussion <
std-discussion_at_[hidden] wrote:

>
>
> On Mon, Jul 1, 2024 at 12:25 PM Daniel Krügler via Std-Discussion <
> std-discussion_at_[hidden]> wrote:
>
>> Am Mo., 1. Juli 2024 um 17:33 Uhr schrieb Yongwei Wu via
>> Std-Discussion <std-discussion_at_[hidden]>:
>> >
>> > On this page <URL:
>> https://en.cppreference.com/w/cpp/container/vector/vector>,
>> > I saw the wording "Move constructor. Constructs the container with the
>> > contents of other using move semantics.... After the move, other is
>> > guaranteed to be empty()."
>> >
>> > Does the standard really provide this empty() guarantee (for vector,
>> > or any other containers)? I cannot find it. I only see the general
>> > specification that a moved-from object is in a valid but unspecified
>> > state.
>> >
>> > (If it does not provide this guarantee, should it?)
>>
>> The wording doesn't say that the post-condition is an empty state, but
>> it has the requirement for all sequence containers (except for
>> std::array) that the move operation has a constant complexity. This
>> more or less implies an empty state for std::vector, since the
>>
>
> "more or less" - yes.
>
> There is only one reasonable way to implement the move constructor for
> std::vector, and it will leave the source object empty.
>
> One can imagine a deliberately hostile implementation of the move
> constructor, which works like this: first, the destination object steals
> the buffer from the source object. Then, only for a trivially copyable type
> such as `int`, the source object attempts to allocate a new buffer and
> construct some elements into it. If the allocation fails, the exception is
> swallowed and the source object is left empty. If the allocation succeeds,
> we have a non-empty source object and the implementation hasn't violated
> any of the rules in the standard.
>
>
>> move-target will typically just "steal" the guts from the move-source.
>> Since you have the valid-but-unspecified guarantee you can call every
>> function without preconditions (Such as size() or capacity()) and
>> inspect the actual situation, if that would be relevant for you.
>>
>> Thanks,
>>
>> - Daniel
>> --
>> Std-Discussion mailing list
>> Std-Discussion_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>>
>
>
> --
> *Brian Bi*
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>

Received on 2024-07-10 17:14:58