[ad_1]
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
varvariable type by a pointer as suggested in the question deletethe pointer in the destructor- implement a copy constructor for
Basetaking care of duplicatingvarby anewallocation
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;
}
};
[ad_2]
solved Will these implementations cause memory leakage?