使用malloc()分配的对象数组的调用构造函数

ARH*_*ARH 3 c c++ oop constructor memory-management

可能重复:
可以以便携方式使用数组的新位置吗?

我想分配对象T的数组并使用对象构造函数初始化对象.使用c ++很容易new:

T * pointerT = new T [arraySize];
Run Code Online (Sandbox Code Playgroud)

它将为所有arraySize对象调用T构造函数.但是,出于某种原因,我必须使用C memalign而不是新的.在这种情况下,我最终使用以下代码

T * pointerT = (T*) memalign(64,arraySize * sizeof(T)); 
new (pointerT) T(); 
Run Code Online (Sandbox Code Playgroud)

new (pointerT) T()只调用T构造函数一次.但是,我需要为所有对象调用T构造函数,而不仅仅是第一个对象.

我非常感谢你的帮助.

Ale*_* C. 8

new (pointerT) T()一个循环.保留pointerT一个对象,其析构函数会销毁对象并调用free(例如调用它aligned_vector),并在构造函数中执行:

ptrdiff_t k = 0;

try
{
    for (; k < n; k++)
        new (pointerT + k) T();
}

catch (...)
{
    for (; k > 0; k--) (pointerT + k)->~T();
    free(pointerT);
    throw;
}
Run Code Online (Sandbox Code Playgroud)

这样,如果构造失败,您可以在事务上挽救,而不是泄漏内存或资源.

为此,最简单的可重用性是实现自己的对齐感知分配器和使用std::vector,它为您处理异常安全(和许多其他好东西).

这是一个示例分配器,C++ 11,具有编译时对齐规范(请建议增强和更正):

template <typename T, size_t align>
struct aligned_allocator
{
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef T& reference;
    typedef const T& const_reference;
    typedef size_t size_type;
    typedef ptrdiff_t difference_type;

    template <typename U>
    struct rebind { typedef aligned_allocator<U, align> other; };

    T* address(T& t) { return &t; }

    T* allocate(size_t n, const T* = 0) 
    {
        if (T* ans = memalign(align, n * sizeof(T))) return ans;
        else throw std::bad_alloc();
    }

    T* deallocate(T* p, size_t) { free(p); }

    size_t max_size() const 
    {
        return size_t(-align) / sizeof(T); 
    }

    template <typename U, typename... Args>
    void construct(U* p, Args&&... args)
    {
        ::new((void *)p U(std::forward<Args>(args)...);
    }

    template <typename U>
    void destroy(U* p) { p->~U(); }
};
Run Code Online (Sandbox Code Playgroud)

示例用法:std::vector<T, aligned_allocator<T, 64>> v(42);构造具有对齐存储和64个元素的向量.

你也可以用C++ 11做

template <typename T, size_t align>
using aligned_vector = std::vector<T, aligned_allocator<T, align>>;
Run Code Online (Sandbox Code Playgroud)

你现在可以使用了

aligned_vector<MyType, 64> v;
Run Code Online (Sandbox Code Playgroud)

并享受异常安全,移动感知,迭代器感知,基于范围的循环感知等,具有对齐存储的向量.