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".