提前道歉,因为这可能是一个愚蠢的第一个帖子。虽然有很多关于这个主题的材料,但对我来说,只有很少一部分是确定的和/或可以理解的。
我有一个AlignedArray
模板类可以在堆上以任意对齐方式动态分配内存(我需要 32 字节对齐 AVX 汇编例程)。这需要一些丑陋的指针操作。
Agner Fog 在 cppexamples.zip 中提供了一个示例类,它滥用联合来执行此操作 ( http://www.agner.org/optimize/optimization_manuals.zip )。但是,我知道写给工会的一个成员然后从另一个成员读取会导致 UB。
AFAICT 将任何指针类型别名为 a 是安全的char *
,但仅限于一个方向。这就是我的理解变得模糊的地方。这是我的课程的精简版AlignedArray
(基本上是对 Agner 的重写,以帮助我理解):
template <typename T, size_t alignment = 32>
class AlignedArray
{
size_t m_size;
char * m_unaligned;
T * m_aligned;
public:
AlignedArray (size_t const size)
: m_size(0)
, m_unaligned(0)
, m_aligned(0)
{
this->size(size);
}
~AlignedArray ()
{
this->size(0);
}
T const & operator [] (size_t const i) const { return m_aligned[i]; }
T & operator [] (size_t const i) { return m_aligned[i]; }
size_t const size () { return m_size; }
void size (size_t const size)
{
if (size > 0)
{
if (size != m_size)
{
char * unaligned = 0;
unaligned = new char [size * sizeof(T) + alignment - 1];
if (unaligned)
{
// Agner:
/*
union {
char * c;
T * t;
size_t s;
} aligned;
aligned.c = unaligned + alignment - 1;
aligned.s &= ~(alignment - 1);
*/
// Me:
T * aligned = reinterpret_cast<T *>((reinterpret_cast<size_t>(unaligned) + alignment - 1) & ~(alignment - 1));
if (m_unaligned)
{
// Agner:
//memcpy(aligned.c, m_aligned, std::min(size, m_size));
// Me:
memcpy(aligned, m_aligned, std::min(size, m_size));
delete [] m_unaligned;
}
m_size = size;
m_unaligned = unaligned;
// Agner:
//m_aligned = aligned.t;
// Me:
m_aligned = aligned;
}
return;
}
return;
}
if (m_unaligned)
{
delete [] m_unaligned;
m_size = 0;
m_unaligned = 0;
m_aligned = 0;
}
}
};
那么哪种方法是安全的(r)?