Re: Realizing memdup() compactly in C++
Nordl?w wrote:
Han anybody written any snippet (template i guess) that realizes memdup
() using the operator new. Suggested name: new_duplicate.
// Array
vector<MyObject>* array;
....
vector<MyObject>* copy = new vector<MyObject>(*array);
// Single Object
class MyObject;
MyObject* obj;
....
MyObject* copy = new MyObject(*obj);
This method does not work with polymorphic types. If you want to support
polymorphic types, you need an abstract clone() method, that is
redefined by any non-abstract class that inherits from MyObject.
// Array w/o wrapper class
MyObject* array;
size_t count;
MyObject* copy = new MyObject[count];
const MyObject* src = array;
const MyObject* src_end = array + count;
MyObject* dst = copy;
while (src != src_end)
*dst** = *src++;
This solution can be encapsulated in a function, of course. But is has
some major disadvantages and therefore I do not recommend to use
something like that.
- First of all the array root and the array size are not encapsulated by
an object and can get out of sync resulting in undefined behavior.
- Secondly the function initialize the destination objects by the
default constructor and assign the content later. This is not very
efficient in general. Of course, you could work around this by using the
placement new operator. This is the way most std::vector implementations
work.
However, there is still the first issue, so why not use std::vector and
forget about new_dup?
Marcel