Type punning, char [] and dereferencing

I have a structure that aims to save user data (i.e. from a plugin). It has one char[]with a given maximum size for storing this data.

struct A
{
    // other members omitted
    // data meant to be type punned, only contains PODs
    char data[256];
};

Then there is an example user structure that has a static function to distinguish itself from A.

struct B
{
    int i;
    double d;

    static B& FromA_ref(A& a)
    {
        // static_assert that sizeof(B) < sizeof(A::data)
        return * reinterpret_cast<B*>(a.data);
    }
};

I am compiling with g++ -O3 -std=c++0x -Wall -o test test.cpp(GCC 4.6.1).

This causes a warning dereferencing type-punned pointer will break strict-aliasing rules. I thought that this would be normal, since I used it char[]as a repository, which I thought would follow the same rules as char*. It seems strange to me that this is not so. Is not it? Well ... I can't change it right now, so let's move on.

Now consider the following method:

struct B
{
    ....
    static B* FromA_ptr(A& a)
    {
        // static_assert that sizeof(B) < sizeof(A::data)
        return reinterpret_cast<B*>(a.data);
    }
}

, GCC . , B.

A a;
auto b = B::FromA_ptr(a);
b->i = 2; // no warnings.

?. , , , . -> - .

, ? .. ( ), ? ( , , A , , memcpy , , , )

+5
1

: , (. SO)

GCC , . , , , GCC - , , .

((may_alias)) , , .

+3

All Articles