On 13.10.2016 23:24, Stefan Ram wrote:
> In a video someone said, there was no small-vector optimization
> anymore. Some requirement of C++11 or C++14 (inadvertently?) made it
> impossible.
Yes, that iterators and references remain valid and refer to the same
items after a swap.
Also, that a swap doesn't copy or swap or move individual items.
I.e. swap really means swapping buffers, not just buffer contents.
• • •
C++11 §23.2.1/8 (a.k.a. container.requirements.general/8):
“The expression a.swap(b), for containers a and b of a standard
container type other than array, shall exchange the values of a and b
without invoking any move, copy, or swap operations on the individual
container elements. Any Compare, Pred, or Hash objects belonging to a
and b shall be swappable and shall be exchanged by unqualified calls to
non-member swap. If
allocator_traits<allocator_type>::propagate_on_container_swap::value is
true, then the allocators of a and b shall also be exchanged using an
unqualified call to non-member swap. Otherwise, they shall not be
swapped, and the behavior is undefined unless a.get_allocator() ==
b.get_allocator(). 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.
”
> But he said that at the same time, people took great care to have a
> small-string optimization. So, how do you store an array of two
> double values in modern C++? I made up the following code. What do
> you think about it?
>
> #include <initializer_list> #include <ostream> #include <iostream>
> #include <string>
>
> int main() { ::std::basic_string< double > s{ 1.2, 3.6 }; ::std::cout
> <<
s.at( 0 )<< '\n'; }
>
Well, in order to properly specialize `std::basic_string` you should
provide a corresponding `std::char_traits`. That doesn't make sense
here. And from that you can conclude, that `std::basic_string` was not
made for this.
I'd simply use a raw array, or possibly a `std::array`.
If you want the predictable/reliable range checking of `at` you can just
code up a little helper function for indexing.
Cheers & hth.,
- Alf