Hi everyone, Let's say I have a base class A, and two derived classes B::A and C::A, such that sizeof(A) < sizeof(B) < sizeof(C). In a parsing routine I need to obtain a pointer to an A object which will be constructed later (since the constructor parameters are not available yet). So I simply allocate the memory and defer the construction to later. The problem is this A object could turn out to be a B or a C, I have no way to know. Hence I allocate the memory to cover the worst case (C). Code: A* a = static_cast( ::operator new(sizeof(C)) ); When the parameters become available, I construct the object using placement new. Notice that some bytes may be left unused if I instantiate a B instead of a C. Code: a = new (a) B(...params...); When the object is no longer needed I simply delete it, as per usual. My hope is that the destructor is adequately called and the allocated memory is released. Code: delete a; So I'd have two questions: - Does deleting directly a B object causes a memory leak, or does it free the entire sizeof(C) patch of memory? - Is this a safe/recommended practice (i.e. are there some better workarounds)? Thanks! Ives
All you have to do is make sure you have allocated enough memory for the object...... You don't need placement-new to demonstrate this. In many "debugging" versions of run-time libraries, a call to malloc() or new[] allocates extra "guard" bytes to detect memory overwrites and corruption..... So for example, a "malloc(10)" or a "new char[10]", need not just allocate 10 bytes. You are guaranteed at least 10 bytes were allocated, but nothing stops an implementation from allocating more.....