[info] Calling an object's constructor
I found out a neat trick earlier. Consider the following code:
Code:
#include <iostream.h>
#include <malloc.h>
class c
{
public:
c();
~c();
};
c::c() { cout << "c Constructed\n"; }
c::~c() { cout << "c Destructed\n"; }
int main()
{
c* p_c = NULL;
p_c = (c*)malloc(sizeof(c));
return 1;
}
In this code, the constructor of class c will never be called. How do we solve this problem. There is another new operator, called placement new. Consider:
Code:
#include <iostream.h>
#include <new>
#include <malloc.h>
class c
{
public:
c();
~c();
};
c::c() { cout << "c Constructed\n"; }
c::~c() { cout << "c Destructed\n"; }
int main()
{
c* mem = NULL;
c* p_c = NULL;
mem = (c*)malloc(sizeof(c));
p_c = new(mem) c; //note how the placement new operator takes in a pointer to a memory address
return (unsigned long(mem)) == (unsigned long)p_c;
}
In the above, new takes in an extra parameter to a memory pointer, and constructs an object in that memory.
I found this interesting, and I was looking for a solution to this problem a few weeks ago, and though someone might need it, or be interested.
Z.