-3

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

GThompson
  • 25
  • 4
  • 6
    No, `reinterpret_cast` does **not** allocate memory! Don't know why you think it does, but it may be time to refresh some basics. – Lukas-T Mar 20 '20 at 14:36
  • 2
    Does this compile? – JohnFilleau Mar 20 '20 at 14:36
  • The reinterpret_cast line sets `ptr` to point to a memory location a few bytes after memory-location zero. That's not a region of memory the program is allowed to access, and in most systems trying to dereference that memory location will lead to an immediate crash. – Jeremy Friesner Mar 20 '20 at 14:37
  • It seems to me like you might need to take a step or two back, and refresh some of your knowledge about pointers and dynamic allocation. Perhaps invest in [a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read as well. – Some programmer dude Mar 20 '20 at 14:37
  • What's the end goal you want to accomplish so that we can help direct you to the correct method. – JohnFilleau Mar 20 '20 at 14:37
  • 1
    You may be looking for "placement new"? – Jesper Juhl Mar 20 '20 at 14:42

1 Answers1

2

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);
walnut
  • 21,629
  • 4
  • 23
  • 59