C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [[packed]] std::unaligned

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 17 Dec 2023 18:47:08 +0000
On Sun, Dec 17, 2023 at 4:17 PM Arthur O'Dwyer wrote:
>
> So in fact you're correct that in order to modify the non-trivially-relocatable
> libstdc++ std::string (which is also available on Godbolt since about a week ago
> when you pass -stdlib=libstdc++), you'd modify the libstdc++ file you listed above.


I've written a specialisation of 'std::relocate' for 'std::string':

        https://godbolt.org/z/hvocroqfc

as follows:

    template<>
    void relocate<std::string>(void *const dst, void *const src) //
Neither 'dst' nor 'src' need be aligned correctly
    {
        using T = std::string;
        using std::byte;
        // Step 1: Copy the bytes
        std::memcpy(dst, src, __datasizeof(T));
        // Step 2: Pluck out the pointer (which might be unaligned)
        // (The pointer is located at offset 0 from 'this')
        byte *p;
        std::memcpy(&p, src, sizeof p);
        // Step 3: Check if the pointer points to within the object
        if ( (p < static_cast<byte*>(src)) || (p >=
(static_cast<byte*>(src)+__datasizeof(T))) ) return;
        // Step 4: Adjust the pointer and copy it into (possibly
unaligned) destination
        p += static_cast<byte*>(dst) - static_cast<byte*>(src);
        std::memcpy(dst, &p, sizeof p);
    }

It works.
Perhaps the programmer could be given two choices:
    * Give your class an extra member - void _Relocate(void
*destination) & noexcept
    * Provide a template specialisation for "std::relocate" (in which
case we should probably just call it _Relocate and keep it outside the
'std' namespace)

Received on 2023-12-17 18:47:03