问题涉及 this post .
一些权威用户表示以下代码中断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;
}
}
但是,我从不使用指向写入数据的指针,而且我从不共享指向它的指针,所以我看不到变量中包含的值如何在编译器没有意识到这一点的情况下发生变化正在发生。我的印象是,也许我违反了一些规则,但不是严格的别名......
注意:我不知道这有多重要,但我的编译器 (gcc 4.9) 不会发出警告。
最佳答案
*((U*) &data)
将违反严格别名,如果这是一个 reinterpret_cast
并且类型 U
不允许别名T
类型。允许的类型出现在 this list 中.
规则引用both reading and writing .
Here是一篇很好的文章,解释了规则背后的一些基本原理。
如主要严格别名线程中所述,您可以使用 memcpy
作为解决方法,例如:
U u;
memcpy( &u, &data, sizeof u );
return u;
在另一个函数中
memcpy( &data, &in, sizeof data );
请注意,类类型的原始字节拷贝受到一些限制(我认为类必须是 POD,并且您最好确保它们具有相同的布局)。
关于c++ - 使用指针转换来存储/转换值 : Am I breaking the strict aliasing rule?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29253100/