tags:

views:

68

answers:

2

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.

+3  A: 

You're printing the address of the variable memAlloc, not the pointer's value.

Replace cout<<"memAlloc : "<<&memAlloc with cout<<"memAlloc : "<< (void*)memAlloc.

André Caron
Thanks for your answer André. Now it´s working. Thank´s a lot!!
EMT
+1  A: 
sbi
It's terribly useful for compatibility with 3-rd party memory allocators or other "special" types of memory (i.e. CUDA's `cuMemAllocHost`) or memory pre-allocated by some other framework (i.e. MATLAB's `mxArray`). If it is not a good idea to use the same allocator for all of your application, using placement is the way to go. In any case, practicing and asking for directions before using it is always a good thing. Don't bash the question!
André Caron
Thank´s for your explanation sbi, It really help me understand more about this topic.
EMT
@André: I don't feel like I was bashing. I think the __why__ question really is an important one to ask, I really believe this not to be a beginner's topic, and I know that there's more to it than what meets the eye. I have done my share of it, but, except for a `std::vector`-lookalike, I'd be hard pressed to come up with what I've needed this for.
sbi
You are right that it is not a beginner's topic, but even if the poster was a beginner (maybe he/she is), exploring out of curiosity is still a good thing, in my opinion. So there is no need to ask why. The part of your post that is interesting is the one where you warn against alignment and state that there is "more to it" than just allocating a buffer of the right size. What I meant by "don't bash the question" is that stating these warnings is a better answer than saying it is "not a beginner's topic" ;-)
André Caron