0

The code I referred is in the link -> http://upcoder.com/3/roll-your-own-vector In this example, in the copyrange method, they are using new operator like in the below code.

  static void
copyRange(T* begin, T* end, T* dest)
{
    while(begin != end)
    {
        new((void*)dest) T(*begin);
        ++begin;
        ++dest;
    }
}

Can anyone explain how new() works in this context?

Can I write new (dest) T(*begin); instead of new((void*)dest) T(*begin); since dest is already a pointer to T. Why should I cast it back to void*?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Thomas Martin
  • 92
  • 1
  • 8
  • Hey, I could use a bit more clarification. Can anyone help me with it. I've edited the question. – Thomas Martin Mar 01 '18 at 13:15
  • There are over 20 versions of [operator new](http://en.cppreference.com/w/cpp/memory/new/operator_new). To make sure we get the `void* operator new(std::size_t count, void* ptr);` version we want, it is customary to cast the pointer parameter to `void*`. Otherwise we just *might* end up with an unexpected user defined operator new for `T*`. – Bo Persson Mar 01 '18 at 13:39

0 Answers0