Craig
Thu Feb 24 16:47:58 CST 2005
"Gabriel Bogdan" wrote:
> Suppose you have a memory pointer to some allocated memory and a
> class. How can you call the constructor of the class so that it
> operates on your memory?
>
> The same question goes for the destructor.
>
> Something like this:
> class A;
> void* tmp_buff;
> ((A*)tmp_buff)->A();
> ((A*)tmp_buff)->~A();
A few suggestions:
- Google for "placement new"
- See
http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.14
- You might want to look at using std::allocator<> in the STL
- You might want to check out Effective C++ by Meyers
The super-simple version of using placement new is...
class A;
void* tmp_buff = get_mem_from_somewhere();
A* a = new(tmp_buff) a;
...use a...
a->~A();
put_mem_back(tmp_buff);
Craig