11

提前道歉,因为这可能是一个愚蠢的第一个帖子。虽然有很多关于这个主题的材料,但对我来说,只有很少一部分是确定的和/或可以理解的。

我有一个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)?

4

2 回答 2

3

我有实现(替换)newdelete运算符的代码,适用于 SIMD(即 SSE / AVX)。它使用以下您可能会觉得有用的功能:

static inline void *G0__SIMD_malloc (size_t size)
{
    constexpr size_t align = G0_SIMD_ALIGN;
    void *ptr, *uptr;

    static_assert(G0_SIMD_ALIGN >= sizeof(void *),
                  "insufficient alignment for pointer storage");

    static_assert((G0_SIMD_ALIGN & (G0_SIMD_ALIGN - 1)) == 0,
                  "G0_SIMD_ALIGN value must be a power of (2)");

    size += align; // raw pointer storage with alignment padding.

    if ((uptr = malloc(size)) == nullptr)
        return nullptr;

    // size_t addr = reinterpret_cast<size_t>(uptr);
    uintptr_t addr = reinterpret_cast<uintptr_t>(uptr);

    ptr = reinterpret_cast<void *>
        ((addr + align) & ~(align - 1));

    *(reinterpret_cast<void **>(ptr) - 1) = uptr; // (raw ptr)

    return ptr;
}


static inline void G0__SIMD_free (void *ptr)
{
    if (ptr != nullptr)
        free(*(reinterpret_cast<void **>(ptr) - 1)); // (raw ptr)
}

这应该很容易适应。显然,您将替换mallocand free,因为您正在使用全局newanddelete用于原始(char)存储。它假设size_t对于地址算术来说足够宽 - 在实践中是正确的,但uintptr_tfrom<cstdint>会更正确。

于 2013-03-07T16:09:43.177 回答
2

要回答您的问题,这两种方法都同样安全。唯一真正令人讨厌的两个操作是强制转换为size_tand new char[stuff]。您至少应该使用uintptr_tfrom<cstdint>为第一个。第二个操作创建了您唯一的指针别名问题,因为从技术上讲,char构造函数在每个char元素上运行,并且构成通过char指针访问数据。你应该malloc改用。

另一个所谓的“指针别名”不是问题。那是因为除了new操作之外,您没有通过别名指针访问任何数据。您只能通过T *对齐后获得的数据访问数据。

当然,您必须记住构造所有数组元素。即使在您的版本中也是如此。谁知道T会放什么样的人。而且,当然,如果你这样做,你必须记住调用它们的析构函数,并且必须记住在复制它们时处理异常(memcpy不要剪切它)。

如果您有特定的 C++11 功能,则不需要这样做。C++11 有一个专门用于将指针对齐到任意边界的函数。界面有点时髦,但它应该可以完成这项工作。该调用在.Thanks中::std::align定义。感谢R. Martinho Fernandes指出。<memory>

这是建议修复的函数版本:

#include <cstdint>  // For uintptr_t
#include <cstdlib>  // For malloc
#include <algorithm>

template <typename T, size_t alignment = 32>
class AlignedArray
{
    size_t m_size;
    void * 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 size() const { return m_size; }

    void size (size_t const size)
    {
        using ::std::uintptr_t;
        using ::std::malloc;

        if (size > 0)
        {
            if (size != m_size)
            {
                void * unaligned = 0;
                unaligned = malloc(size * sizeof(T) + alignment - 1);
                if (unaligned)
                {
                    T * aligned = reinterpret_cast<T *>((reinterpret_cast<uintptr_t>(unaligned) + alignment - 1) & ~(alignment - 1));

                    if (m_unaligned)
                    {
                        ::std::size_t constructed = 0;
                        const ::std::size_t num_to_copy = ::std::min(size, m_size);

                        try {
                            for (constructed = 0; constructed < num_to_copy; ++constructed) {
                                new(aligned + constructed) T(m_aligned[constructed]);
                            }
                            for (; constructed < size; ++constructed) {
                                new(aligned + constructed) T;
                            }
                        } catch (...) {
                            for (::std::size_t i = 0; i < constructed; ++i) {
                                aligned[i].T::~T();
                            }
                            ::std::free(unaligned);
                            throw;
                        }

                        for (size_t i = 0; i < m_size; ++i) {
                            m_aligned[i].T::~T();
                        }
                        free(m_unaligned);
                    }
                    m_size = size;
                    m_unaligned = unaligned;
                    m_aligned = aligned;
                }
            }
        } else if (m_unaligned) { // and size <= 0
            for (::std::size_t i = 0; i < m_size; ++i) {
                m_aligned[i].T::~T();
            }
            ::std::free(m_unaligned);
            m_size = 0;
            m_unaligned = 0;
            m_aligned = 0;
        }
    }
};
于 2013-03-07T16:30:54.163 回答