Answer the question
In order to leave comments, you need to log in
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]));
}
};
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question