heLomaN
heLomaN

Reputation: 1804

Is it safe to call placement new on address of elements in std::array?

I want to reuse memory declared in std::array. So at the beginning, declare a variable:

std::array<S, 1024> pool;

Then I want destroy some elements and reuse it for other purpose:

(&pool[24])->~S();
new (&pool[24])->S();

Is it safe? What should I take care of?

Upvotes: 1

Views: 151

Answers (1)

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12332

Since c++20 this is perfectly legal as long as both the destructor and constructor are called. If they throw an exception then you are in trouble. At some point the destructor for the array will call ~S() again and if there isn't a living object in the array things will go badly.

So in summary: It's dangerous.

A better solution, if you don't want to use heap allocated objects, would be to create a Memory Resource with the size of 1024 S and an allocator for it and use that.

Upvotes: 1

Related Questions