Tuesday, January 12, 2010

C++ new operator and object cloning.

STL provides a few operator overloadings for the global new operator, which is used by new keyword to allocate a memory block to make a instance. New operators only provide a service for allocation of memory.

These come with header file new.
When you declare it, it will apply the global namespace.

http://www.cplusplus.com/reference/std/new/

You can allocate a memory block for a uninitialized object(, which means its constructor has yet been called) and initialize with its constructor later.

For instance, using this feature, you can do a cloning for a object.

--------------------------------------------------------------------------------

#include iostream
#include stdlib
#include new
using namespace std;

struct myclass {
myclass(int i):m_i(i) {cout << "myclass constructed\n";}
myclass(myclass &src) {
this->m_i = src.m_i;
}

void print() { cout << "my member is " <<>m_i << endl; }

int m_i;
};

int main() {
myclass tmp(1);

myclass *p3 = (myclass *)malloc(sizeof(myclass));

new(p3) myclass(tmp); // call constructor
//operator new (sizeof(myclass), p3);

p3->print();

return 0;
}

0 comments:

Post a Comment