Preventing the destruction of member variables

181 views Asked by At

I suspect it is not possible, but in the situation below having created A and B I'd like to reuse B (by placing it into a stack ready for reuse) but delete A. They are two of many classes derived from the parent class and I'd like the code responsible for deleting objects to be able to behave the same for all derived objects.

Is it possible to override Derived2's destructor/delete operator such that data2's destructor isn't called? Then it would be a simple matter to put B into the stack with all of the data allocated during its construction ready for reuse.

(EDIT: For clarification, I want to reuse B which has a large number of member variables of different types depending on which derived class is involved. I do appreciated all suggestions but I used a very simple example to find out if this particular approach was possible and because the actual classes contain a huge amount of extra code irrelevant to the question at hand)

class Parent{
    ...
};

class Derived1:Parent{
    DataClass data1;
};

class Derived2:Parent{
    DataClass data2;
};

Derived1* A = new Derived1();
Derived2* B = new Derived2();
delete A;
delete B;

Would doing that (if it were possible) be considered a breach of the RAII design pattern?

2

There are 2 answers

6
AudioBubble On BEST ANSWER

*SNIP - After clarification of the scenario, I posted this answer in a comment originally *

How about this. In your stack, store unique_ptrs. When you pop from the stack, you grab the raw pointer from the unique_ptr and shove it into another unique_ptr - this second one is declared with a custom deleter which, on destruction, retains the location of the stack and performs the reverse of the pop operation. This will work with shared_ptr too but obviously it depends on what you need.

It's independent of the type of B, and could be encapsulated entirely in the stack class (barring the unique_ptr+deleter type, but that would just be a typedef).

0
Paweł Stawarz On

Instead of storing data2 by value, store it using a pointer and allocate it in the constructor. That way it won't get deleted when you delete the B (unless you call delete inside Derived2 destructor).