C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::sizeof_minus_trailing_padding

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Fri, 1 Dec 2023 23:38:36 +0000
On Thu, Nov 30, 2023 at 8:36 PM Arthur O'Dwyer
<arthur.j.odwyer_at_[hidden]> wrote:
>
>
> This is the `__datasizeof` builtin. In chronological order:
> https://orodu.net/2023/01/15/trivially-relocatable.html (Ctrl+F data_size_of)
> https://quuxplusone.github.io/blog/2023/02/24/trivial-swap-x-prize/#if-stdswap-cant-memcpy-then-how-do-we-trivially-swap
> https://clang.llvm.org/docs/LanguageExtensions.html#implementation-defined-keywords


I think I just managed to write '__datasizeof' using portable standard C++:

    #include <cstddef> // offsetof, size_t
    namespace std {
        template<typename T>
        consteval size_t datasizeof(void) noexcept
        {
            struct Dummy {
                [[no_unique_address]] T obj;
                char c;
            };

            return offsetof(Dummy,c);
        }
    }

When I first wrote this, I thought it might not work with classes that
have a private constructor (or which don't have a constructor that
takes no arguments), but it works with every type.

Here it is in action working on GodBolt with a few compilers (Intel,
GNU g++, LLVM clang++):

        https://godbolt.org/z/xecsofecx

It compiles successfully on MSVC++ too but it always yields the same
result as 'sizeof' because MSVC++ doesn't do overlapping objects.

Received on 2023-12-01 23:38:49