C++ Logo

sg12

Advanced search

Re: [ub] launder and aliasing

From: Howard Hinnant <howard.hinnant_at_[hidden]>
Date: Fri, 26 Feb 2016 17:06:41 -0500
On Feb 26, 2016, at 4:46 PM, Richard Smith <richardsmith_at_[hidden]> wrote:
>
> Gaby had a paper that would guarantee that memcpy can be used to
> reinterpret the bytes of an object of one type as a value of another
> type; that would seem to fit the bill here. And you can use that to
> build higher-level operations, such as this:
>
> template<typename T, typename U> T *change_object_type(U *p) {
> static_assert(sizeof(T) == sizeof(U));
> static_assert(is_trivially_copyable_v<T> && is_trivially_copyable_v<U>);
> char buffer[sizeof(T)];
> memcpy(buffer, p, sizeof(T));
> p->~U();
> T *result = new (p) T;
> memcpy(result, buffer, sizeof(T));
> return result;
> }
>
> int foo(float f) {
> int *i = change_object_type<int>(&f); // float is dead, long live the int!
> return *i;
> }

Adding this might be another nice check:

    static_assert(alignof(T) <= alignof(U));

Howard

Received on 2016-02-26 23:06:44