The 1st alternative will cause a memory leak whether you pass true
or false
to the constructor of Derived
. Exactly one Structure
will be allocated on the heap, which is then copied by the default copy constructor of Structure
when the assignment
var = structure;
is executed.
If you:
- replace the internal
var
variable type by a pointer as suggested in the question delete
the pointer in the destructor- implement a copy constructor for
Base
taking care of duplicatingvar
by anew
allocation
you should not have any problem.
struct Structure {
int a;
int b;
Structure() { a=1; b=2; }
Structure(int num1, int num2) : a(num1), b(num2){}
};
class Base {
private:
Structure *var;
public:
Base(Structure *structure) {
var = structure;
}
Base(const Base &b) {
var = new Structure(*b.var);
}
virtual ~Base(){
delete var;
var = 0;
}
};
solved Will these implementations cause memory leakage?