使用指针转换来存储/转换值:我打破严格别名规则吗? [英] Using pointer conversions to store/cast values: Am I breaking the strict aliasing rule?

查看:148
本文介绍了使用指针转换来存储/转换值:我打破严格别名规则吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与此信息有关。

有些权威用户表示,以下代码会中断严格别名规则

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...

注意:我不知道这是多少,但我的编译器(gcc 4.9)不会发出警告。

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

推荐答案

*((U *)& data)如果 reinterpret_cast 且类型 U 不允许,则将违反严格别名别名类型 T 。允许的类型会显示在此列表中。

*((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.

该规则以阅读和写作

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

如主要的严格别名线程所示,你可以使用 memcpy 作为工作,例如:

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;

和其他功能

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

请注意,类类型的原始字节副本受到一些限制(我认为类必须POD,你最好确保他们有相同的布局)。

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).

这篇关于使用指针转换来存储/转换值:我打破严格别名规则吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆