Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting the "this" pointer to another type does not violate strict aliasing?

So if I do something like this:

#include <ios>

using std::forward;

template<class T>
struct pod_version final{
    private:
        alignas(T) uint8_t m_data[sizeof(T)];
    public:
        pod_version()=default;
        pod_version(const pod_version&)=default;
        pod_version(pod_version&&)=default;
        ~pod_version()=default;
        pod_version& operator=(const pod_version&)=default;
        pod_version& operator=(pod_version&&)=default;

        template<class...V>void construct(V&&...v){
            new (m_data) T(forward<V>(v)...);
        }

        void destroy(){
            reinterpret_cast<T*>(m_data)->~T(); // g++: warning typed punned blah im allowed to break ur code LOL
            reinterpret_cast<T*>(this)->~T(); // g++: :D
        }
};

int main(){
    pod_version<int> x;
    x.construct(5);
    x.destroy();
    return 0;
}

Note: "m_data" and "this" should point to the same place...

gcc 4.8.1

like image 337
Mike Avatar asked Nov 10 '22 15:11

Mike


1 Answers

Use char, not uint8_t.

The type punning rules have a special case for char, signed char, and unsigned char, and ONLY these types. uint8_t is not required to mean one of them.

Note that the whole concept of this pod_version class is suspect. You're forcing trivial copy semantics on types for which they are not valid. Your code will attempt to call a destructor on uninitialized memory, or on a binary image of an object. Both will result in undefined behavior.

like image 164
Ben Voigt Avatar answered Nov 14 '22 22:11

Ben Voigt