C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sat, 23 Dec 2023 10:20:55 +0000
On Thu, Dec 21, 2023 at 10:49 PM Julien Villemure-Fréchette via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> FWI, std::basic_string<long
> double> is not a well chosen example as 'long double' is not a character container type: std::char_traits<long double> need not be defined by an implementation (and should probably not be). The primary template for std::char_traits could as well be left undefined.
>
> At least, it would be more appealing to use a more sensible type as a toy example, say std::u32string (AKA std::basic_string<char32_t>).


I've replaced 'long double' with 'char32_t', and also I've written an
optimised specialisation of 'std::aligned' for when 'alignof(T)' is 1.
So where we had one function:

        constexpr unaligned &operator=(unaligned const &rhs) noexcept(
noexcept(std::declval<T&>() = rhs) )
        requires (std::is_copy_assignable_v<T> &&
!std::is_trivially_copy_assignable_v<T>)
        {
            alignas(T) std::byte buf[ __datasizeof(T) ];
            T &tmp = *static_cast<T*>(static_cast<void*>(buf));
            _Relocate<T>(&tmp, &_m_data.front());
            tmp = rhs;
            _Relocate<T>(&_m_data.front(), &tmp);
            return *this;
        }

We now have two functions (one for alignof(T)==1u and one for all others).

        constexpr unaligned &operator=(unaligned const &rhs) noexcept(
noexcept(std::declval<T&>() = rhs) )
        requires ((1u!=alignof(T)) && std::is_copy_assignable_v<T> &&
!std::is_trivially_copy_assignable_v<T>)
        {
            alignas(T) std::byte buf[ __datasizeof(T) ];
            T &tmp = *static_cast<T*>(static_cast<void*>(buf));
            _Relocate<T>(&tmp, &_m_data.front());
            tmp = rhs;
            _Relocate<T>(&_m_data.front(), &tmp);
            return *this;
        }

        constexpr unaligned &operator=(unaligned const &rhs) noexcept(
noexcept(std::declval<T&>() = rhs) )
        requires ((1u==alignof(T)) && std::is_copy_assignable_v<T> &&
!std::is_trivially_copy_assignable_v<T>)
        {
            T &tmp = *static_cast<T*>(static_cast<void*>(&_m_data.front()));
            tmp = rhs;
            return *this;
        }

GodBolt: https://godbolt.org/z/7M6GMEGce

Received on 2023-12-23 10:20:40