Hello, I have been trying to understand the Placement new concept. I searched on the internet for some examples. And with all that info I created one example myself, here´s the code:
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
class MyClass
{
private:
size_t num;
public:
~MyClass(void) { cout<<"DESTRUCTOR"<<endl; };
void print(void) { cout<<num<<endl; };
void set(size_t num) { this->num = num; };
};
int main(void)
{
/** Just a little test */
MyClass* myClass = new MyClass;
myClass->set(32);
myClass->print();
delete myClass;
/***/
//Placement new code sample.
char* memAlloc = new char[sizeof(MyClass)];
cout<<"memAlloc : "<<&memAlloc<<endl;
MyClass* ptr = new(memAlloc) MyClass;
ptr->set(95);
ptr->print();
cout<<"ptr : "<<ptr<<endl;
ptr->~MyClass();
delete[] memAlloc;
return 0;
}
As I understand ptr will use the memory allocated by memAlloc with placement new. In this case, memAlloc and ptr will have the same address in memory? I tried to print it (a you sure see) but get different results. Using Code Blocks IDE with gcc 4.4.1 :
memAlloc : 0x22ff04
ptr : 0x2e1038
Can this be possible?, Am I printing it the wrong way?
Thanks a lot for any advice.