Re: [PATCH 2/4] gdbsupport: add array_view copy function

Simon Marchi
2021-11-18T20:07:49Z

On 2021-11-16 7:20 p.m., Tom Tromey wrote:
>>> In C++20 I think we could use std::copy by having the array view
>>> iterators implement the contiguous_iterator concept. So, maybe a
>>> comment to this effect would be good.
>
> Simon> Do you mean we could use std::copy to implement this copy function,
> Simon> instead of using memcpy, and that would deal with the details of copying
> Simon> in the most efficient manner?
>
> Yeah, but IIUC it will only use memcpy or whatever if it sees the
> contiguous_iterator concept (and if the content type is trivially
> copyable). I'm not sure if there's a way to get this behavior before
> C++20 though.
>
> Tom
>

I did some tests (with g++ 11, if that matters), compiled GDB with
-std=c++11, and it seems like std::copy does the right thing. When
copying a trivial type (array_view<int>), it ends up using
this __builtin_memmove:

https://gitlab.com/gnutools/gcc/-/blob/6f4ac4f81f89caac7e74127ed2e6db6bbb3d7426/libstdc++-v3/include/bits/stl_algobase.h#L414-434

When copying a type that has a user-defined copy assignment operator, it
ends up using this manual loop:

https://gitlab.com/gnutools/gcc/-/blob/6f4ac4f81f89caac7e74127ed2e6db6bbb3d7426/libstdc++-v3/include/bits/stl_algobase.h#L394-412

That seems to be exactly what we want.

Also, reading about std::copy made me realize that we would have to make
sure we handle overlapping ranges correctly. Using std::copy or
std::copy_backwards (depending on whether the destination comes before
the source) handles that.

I will post an updated series.

Simon