[ub] launder and aliasing

Howard Hinnant howard.hinnant at gmail.com
Fri Feb 26 23:06:41 CET 2016


On Feb 26, 2016, at 4:46 PM, Richard Smith <richardsmith at googlers.com> 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



More information about the ub mailing list