Hex Crown
Hex Crown

Reputation: 763

What is the proper way to "placement new" an array of structs/classes with a generic member variable?

Given the following class:

template<class T, std::size_t N>
class Example {
    struct Element {
        std::size_t id;
        std::aligned_storage_t<sizeof(T), alignof(T)> actual_data;
    };
    std::array<Element, N> data;

public:
    template<typename ...Args>
    void emplace_insert(Args&&... args) {
        auto some_id = 123; //for example

        //placment new 
        new (&data[some_id]) Element(some_id, T(std::forward<Args>(args)...));
    }
};

How would I go about using the placement new on data in the emplace_insert function? Do I need to define a custom constructor for the Element struct, and if so, how would I go about passing the arguments for the aligned_storage_t?

I'm using the aligned storage to prevent default construction.

Now for the final question, I realize this one might be more opinion based, but I'm still hoping I could get some sort of answer.

Would it be better to just maintain a 2nd array that contains the id rather than trying to combine the two?

Upvotes: 4

Views: 263

Answers (1)

L. F.
L. F.

Reputation: 20619

Your data is an array, and the Elements themselves are properly initialized. It is actual_data that you should use placement new on.

data[some_id].id = some_id;
new (&data[some_id].actual_data) T(std::forward<Args>(args)...);

That said, why do you maintain id in the element? It is already taken care of by std::array.

Upvotes: 2

Related Questions