Search code examples
c++pointersreinterpret-cast

Placement of an item in memory


Help me please. I allocate memory as follows (T is template type)

T * ptr = reinterpret_cast<T*>(operator new (sizeof(T));

And after that I want to put an element into this memory; Am I write if I do it in this way?

new (p) T(elem);

(elem has type T)

UPD: sorry, it's a mistake that I forget to write operator new


Solution

  • reinterpret_cast does not allocate memory. I don't know how you got the impression that it does.

    T * ptr = reinterpret_cast<T*>((sizeof(T));
    

    This (assuming it is supported in the first place) takes the size of the type T which is an integer value and reinterprets it in an implementation-defined matter as a pointer-to-T value.

    So if e.g. the size of T is 16, then ptr will probably be a pointer to the address 16.

    This clearly makes no sense.

    The usual function to dynamically allocate memory to place objects into later is operator new:

    void* mem_ptr = operator new(sizeof(T));
    T* ptr = new(mem_ptr) T(elem);