Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c++ - Using pointer conversions to store/cast values: Am I breaking the strict aliasing rule?

The question relates to this post.

Some authoritative users stated that the following code breaks strict aliasing rules.

#include <boost/static_assert.hpp>

template <typename T>
struct MyType {

    private:
    T data;

    public:
    template <typename U>
    operator U () {
        BOOST_STATIC_ASSERT_MSG(sizeof(U) == sizeof(T),"Trying to convert to data type of different size");
        return *((U*) &data);
    }

    template <typename U>
    NeonVectorType<T>& operator =(const U& in) {
        BOOST_STATIC_ASSERT_MSG(sizeof(U) == sizeof(T),"Trying to copy from data type of different size");
        data = *((T*) &in);
        return *this;
    }
}

However, I am never using a pointer to write data, and I am never sharing a pointer to it, so I cannot see how value contained in a variable can change without the compiler realizing that this is happening. My impression is that maybe I am breaking some rules, but not the strict aliasing ones...

Note: I don't know how much this matters, but my compiler (gcc 4.9) does not issue warnings.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

*((U*) &data) will violate strict aliasing if this is a reinterpret_cast and the type U is not permitted to alias the type T. The permitted types appear in this list.

The rule refers to both reading and writing.

Here is a good article that explains some of the rationale behind the rules.

As noted on the main strict aliasing thread, you can use memcpy as work around , for example:

U u;
memcpy( &u, &data, sizeof u );
return u;

and in the other function

memcpy( &data, &in, sizeof data );

Note that raw byte copies of class types are subject to some restrictions (I think the classes have to be POD, and you'd better be sure they have the same layout).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...