Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

Array placement new in combination with _aligned_malloc, what's the proper way to delete?

Started experimenting with placement new and delete along with memory alignment and it feels like being brainy smurf in papas smurf's lab.

Lets say I have an object e.g.,

struct obj {
...
};

and I want to allocate in aligned storage an array with N such objects. What I do is:

obj *buf = new (static_cast<obj*>(_aligned_malloc(sizeof(obj) * N, 64))) obj[N];

That is, I use placement new in combination with _aligned_malloc.

Q

P.S I know that _aligned_malloc is not standard but rather MVSC specific.

Upvotes: 2

Views: 507

Answers (1)

mpiatek
mpiatek

Reputation: 1343

Isn't it sufficient for your task to use C++11 alignas?

For the question regarding delete[] - aligned_malloced memory should be freed using _aligned_free. Of course you need to call destructor first. Look this answer.

EDIT:

#include <malloc.h>

__declspec(align(64))
struct obj
{
    int i;
    char c;

    obj() : i{ 1 }, c{ 'a' } {}

    void* operator new[](size_t n)
    {
        return _aligned_malloc(n, 64);
    }

    void operator delete[](void* p)
    {
        _aligned_free(p);
    }
};

int main()
{
    int N = 10;
    obj *buf = new obj[N];

    buf[2].i = 1;

    delete[] buf;
    return 0;
}

On my machine it creates properly aligned storage, c-tors and d-tors are called because of new[] and delete[] instead of manual malloc/free.

Upvotes: 1

Related Questions