F
F
floppa3222022-01-14 12:50:13
C++ / C#
floppa322, 2022-01-14 12:50:13

How to properly allocate raw memory to place objects in it?

Is there a way to initialize "raw" static memory for objects without calling their constructors?

Code example:

template<typename T, size_t capacity>
class Container
{

private:

    alignas(alignof(T)) uint8_t buffer[sizeof(T) * capacity];
    size_t size = 0;

public:

    ~Container()
    {
        for (size_t i = 0; i < size; ++i)
        {
            (reinterpret_cast<T *>(&buffer[sizeof(T) * i]))->~T();
        }
    }

    void add(const T & element)
    {
        new (&buffer[sizeof(T) * size]) T(element);
        ++size;
    }

    const T & get(size_t i)
    {
        return *(reinterpret_cast<T *>(&buffer[sizeof(T) * i]));
    }

};


Here's a workaround that came to mind. But, to be honest, they confuse reinterpret casts :), I would like to do without them, through the usual T buffer[capacity], but without calling constructors.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2022-01-14
@gbg

No, if you didn't call the constructor and access the object, you'll collapse UB, technically speaking.
And what's the point of allocating memory and not calling constructors? This violates the RAII principle at the very least.
By the way, I did not see static memory in your code.
So from the outside it all looks like an XY problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question