Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

question for vector::data() ptr after vector::swap()

26 views
Skip to first unread message

anhongl...@gmail.com

unread,
Dec 27, 2018, 1:13:02 AM12/27/18
to
Hi all,

I am pretty new to the c++ language, I have a question for vector swap:

std::vector<int> a(10);
auto p = a.data();

std::vector<int> b;
b.swap(a);

assert(b.data() == p);

Is there any possibility that the assertion would fail here?
I tried seems the eq holds, but is there any guarantee in the standard doc?



Thanks,
Anhong

ViralTaco

unread,
Dec 27, 2018, 1:53:56 AM12/27/18
to
Actually no. (Unless there is a specific behaviour I'm unaware of)
It should be the same as
`assert(a.data() == a.data());`
Since you use std::swap(). https://en.cppreference.com/w/cpp/container/vector/swap2

(cf: https://godbolt.org/z/p_RA0X )

Alf P. Steinbach

unread,
Dec 27, 2018, 8:10:33 AM12/27/18
to
The current standard guarantees that for reversible containers in general

C++17 §26.2.1/11.6
“no swap() function invalidates any references, pointers, or iterators
referring to the elements of the containers being swapped”

That's the reason why std::vector can't use the small buffer
optimization, while std::string can.

Additionally there is a clarification, which curiously comes before the
guarantee that's clarified:

C++17 §26.2.1/9
“Every iterator referring to an element in one container before the swap
shall refer to the same element in the other container after the swap.
It is unspecified whether an iterator with value a.end() before the swap
will have value b.end() after the swap.”

At the level of iterators one could have worked around things, and
possibly provided the small buffer optimization.

But the guarantee for pointers and references prevents that.


Cheers & hth.,

- Alf

Öö Tiib

unread,
Dec 27, 2018, 9:27:02 AM12/27/18
to
Note that here is likely a question about desirability and practicality.

The small buffer optimization is usually vital with strings. The
vast majority of texts stored (some sort of ids, names, codes,
phone numbers) are under 30 bytes long.

With std::vector we can't judge that so generally. It is likely
a corner case where we need a lot of often little vectors.
When someone really is in situation where the optimization
helps then they can perhaps use for their container
std::basic_string<TheirStuff,TheirTraits>? It is 13
trivial functions to write that TheirTraits and if they are into
such optimizations then they get (likely also useful) std::basic_string_view<TheirStuff,TheirTraits> as a
bonus! ;)

Minutiae: std::string is usually implemented to use 32
bytes on 64-bit platforms while std::vector is usually
implemented as 24 bytes long. It is very likely for to
tap that vein.
0 new messages