0

Today I saw a strange initialization of a pointer. It looks like this:

struct A
{
  void* data;
  int bufLen;
  ...
}

void fun(A* a, int* result)
{
  SomeClass* b = new (a->data) SomeClass();
}

It's completely fine, it does compile, it does work, but I don't know why. I'd like to know what's going on with the initialization of the variable b. Is it a cast? Is it a copy of the variable a->data in a new memory slot?

Astinog
  • 1,151
  • 3
  • 12
  • 35
  • 8
    It's called [placement `new`](https://isocpp.org/wiki/faq/dtors#placement-new). – Biffen Jul 04 '16 at 09:28
  • 1
    Possible duplicate of [What uses are there for "placement new"?](http://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new) – 463035818_is_not_an_ai Jul 04 '16 at 09:48
  • Thank you @Biffen. One question: for example, can I use the `SomeClass` variable to pass information to another thread? If I can, do I need anyway to call the descrutor in the `fun` function? – Astinog Jul 04 '16 at 12:24
  • **1** Yes. **2** It depends. This has nothing to do with placement `new`, though. – Biffen Jul 04 '16 at 12:26
  • In the webpage you linked it says that I need to call explicitly the destructor in this case. My first thought was that if I deallocate that specific part of memory then this means that it can be used for other purpose. But I need to read that part of memory from another thread before it can be used again by some else. – Astinog Jul 04 '16 at 12:29

1 Answers1

2

It's called placement new and it's generally used to place an object in a specified address in memory.

In your code, an object of type SomeClass will be placed at the memory location of a->data.

To use it, you can overload the operator new by yourself, or use the ones already defined in the Standard Library, contained in the header file <new>.

Mattia F.
  • 1,720
  • 11
  • 21