1

I met with some codes as below.

char *buffer = new char[sizeof(PoolThread) * numThreads];
m_threads = reinterpret_cast<PoolThread*>(buffer);
for (int i = 0; i < numThreads; i++)
{
    new (buffer)PoolThread(*this);
    buffer += sizeof(PoolThread);
}

I guess the new here is for initializing the empty memory space pointed to by m_threads to a real object (of PoolThread class)

I've googled, but only found infos of usage of new like this:

pointer = new somthing[number]; 

I hope more info of the usage of new in my upper code example. And does this usage comes from c++ standard?

awesoon
  • 32,469
  • 11
  • 74
  • 99
Robert Bean
  • 851
  • 2
  • 11
  • 21
  • See ["What uses are there for “placement new”? "](http://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new). – Kijewski May 23 '13 at 03:56
  • Yes, I'm asking a duplicate question. I'll pick jack's answer after 7 mins – Robert Bean May 23 '13 at 04:02
  • Yes, mine is duplicate question with that. – Robert Bean May 23 '13 at 04:03
  • 1
    The real question is: why this code and not `std::vector m_threads{numThreads, PoolThread{*this}};`. I am thinking that maybe `PoolThread` is not copiable ? – Matthieu M. May 23 '13 at 06:13
  • I think the programmer is avoiding std containers, I've read codes for a whole day, he just writes all data structures by himself. I've also heard that std containers are not samely implemented on different platforms. So, I guess vector is not used because of such concerns. – Robert Bean May 23 '13 at 06:18

1 Answers1

7

That is a placement new and it is used when you want to override the normal memory manager of the OS and choose exactly where you want to place an object that you are allocating.

In the code you posted, buffer address is used to specify where the element will be allocated (in fact it is modified so that every consecutive allocation follows the address).

Of course, since it frees the memory manager from the duty of memory allocation, it is your own responsibility to provide valid addresses for what you are storing. That's why is it used just when it is really needed.

Jack
  • 131,802
  • 30
  • 241
  • 343