Yes, this is possible. std::vector
does this, in that it allocates buffers with space for objects, then conditionally constructs them (in-place) and destroys them, managing the memory independently of the object lifetime.
In C++11, I'd use a union
of your type and a small type with trivial constructors/destructors to indicate a memory location that can fit your type, but doesn't have to have that type in it. External to that you have to track if the object is actually there. Creating the item consists of using placement new
, and destroying it consists of manually calling the destructor.
The buffer of the union
objects, be it N objects or 1, would be managed completely independently. The default constructor of the union
would either construct nothing, or construct the trivial type (in which case you might want to destroy that trivial type).
However, odds are that the real answer to your question is "don't do that". And if you do that, you wrap the pointers in a class
whose only job is handling the above mess. Classes of that type (whose job is to manage a pointer's lifetime and pointer-like properties) are called "smart pointers".
delete
/free
? – Electoraldelete
/free
without calling the destructor. – Gallicanismnullptr
, thendelete
ing them will be a no-op. – Cesuradelete
calls the destructor. – Penneydelete
does two things; call the destructor then deallocate memory. If you set the pointer tonullptr
you're not just avoiding the destructor, you're also not doing the deallocation. You have explicitly said you do want deallocation, therefore setting the pointer tonullptr
does not achieve what you've asked. – Pascaledelete
the internal pointers (since that's what this wrapping object's destructor does). So I suggested to set the interal pointers tonullptr
to notdelete
them when still executing the outer object's destructor properly. – Cesura