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?

5
  • 8
    It's called placement new. Commented Jul 4, 2016 at 9:28
  • 1
    Possible duplicate of What uses are there for "placement new"? Commented Jul 4, 2016 at 9: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? Commented Jul 4, 2016 at 12:24
  • 1 Yes. 2 It depends. This has nothing to do with placement new, though. Commented Jul 4, 2016 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. Commented Jul 4, 2016 at 12:29

1 Answer 1

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>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.