C++ Logo

std-proposals

Advanced search

Re: [std-proposals] static_assert instead of undefined behaviour

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Fri, 11 Oct 2024 12:54:45 +0100
On Fri, 11 Oct 2024 at 09:10, Frederick Virchanza Gotham via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> I wrote code yesterday to manipulate VTables:
>
> #ifdef _MSC_VER
> struct VTable {
> RTTICompleteObjectLocator *locator;
> void *funcptrs[1u];
> };
> #else
> struct VTable {
> std::uintptr_t top_offset;
> std::type_info *p_type_info;
> void *funcptrs[1u];
> };
> #endif
>
> static_assert( std::is_standard_layout_v<VTable> );
> constexpr std::size_t vtable_prologue_size = offsetof(VTable,
> funcptrs);
>
> See how I use the 'static_assert' to be sure that the 'offsetof' won't
> have undefined behaviour? Well I think the Standard should be changed
> so that if you use 'offsetof' on an inappropriate type, then you get a
> compile-time static_assert failure rather than undefined behaviour at
> runtime.
>

There is no undefined behaviour, and it already works how you want.

"Use of the offsetof macro with a type other than a standard-layout class
(11.2) is conditionally-supported."

That means either it compiles and works, or it's ill-formed and you get a
compile-time diagnostic.



>
> There might be a handful of other things in the Standard that could be
> changed this way too. Better to have static_assert's failing at
> compile time.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2024-10-11 11:56:06