0

I am reviewing Facebook folly's lock free queue and am unfamililar with an approach they're using.

In the write() function, they use syntax

new (&records_[currentWrite]) T(std::forward<Args>(recordArgs)...);

I would have expected something more along the lines of

records_[currentWrite] = ....

I know im missing something, but if someone could kindly explain the use of new here, as i would have thought that creating a heap variable would have an overhead consequence.

if (nextRecord != readIndex_.load(std::memory_order_acquire)) {
    new (&records_[currentWrite]) T(std::forward<Args>(recordArgs)...);
    writeIndex_.store(nextRecord, std::memory_order_release);
    return true;
}

https://github.com/facebook/folly/blob/master/folly/ProducerConsumerQueue.h

Thanks!

awaugh
  • 75
  • 1
  • 6
  • 3
    You should do some research about *placement new*. – Some programmer dude Jul 13 '17 at 06:09
  • That's a "placement new", and it's used to "run the constructor for the object, when the memory has already been allocated. Will find the relevant "what is placement new" question and link as duplicate... – Mats Petersson Jul 13 '17 at 06:10
  • Scott Meyers book "More Effective C++" in its Item 8 talks about "placement new" and has examples about how it is used. I think it is a good reading on the subject. – Jorge Y. Jul 13 '17 at 06:14
  • excellent thanks for your feedback. I was unsure of the keyword i should be searching for, ill review the above suggestions. – awaugh Jul 13 '17 at 06:17

0 Answers0