How can a class know, that it should not free its allocated memory in the destructor. Because the class is a pointee to a pointer?
Some example code (untested) that does not work.
The problem is at the constructor of MyOtherClass
.
class MyClass {
~MyClass() { free(...); } // free some vars, does not matter what.
};
class MyOtherClass {
MyClass *m_ptr;
MyOtherClass(MyClass pointee) {
m_ptr = &pointee;
// when this constructor is finished, the destructor of parameter "pointee" will be called.
// and therefore the attribute "m_ptr" points to nothing.
}
};
Could it be possible that MyClass
uses something like this?
class MyClass {
bool i_am_a_pointee = false; // but how and where to assign this?
~MyClass() {
if (!i_am_a_pointee) { free(...); }
}
};
The goal is to create a container like class for multiple different classes. But with pointers.
Code:
class MyClassA {
MyClassA() {}
// here the pointer is cleared because that is required for my class.
// So when the var goes out of scope like in the constructor of "MyContainer(MyClassB)" all the vars will be deleted and therefore the pointer technically points to nothing.
~MyClassA() { free(...); }
};
class MyClassB {
MyClassB() {}
// here the pointer is cleared because that is required for my class.
// So when the var goes out of scope like in the constructor of "MyContainer(MyClassB)" all the vars will be deleted and therefore the pointer technically points to nothing.
~MyClassB() { free(...); }
};
class MyContainer {
MyClassA *m_class_a;
MyClassB *m_class_b;
MyContainer(MyClassA x) {
m_class_a = &x // here the problem.
}
operator MyClassA() {
return *m_class_a;
}
MyContainer(MyClassB x) {
m_class_b = &x // here the problem.
}
operator MyClassB() {
return *m_class_b;
}
};
int main() {
MyContainer container;
MyClassA a;
MyClassB b;
container = a; // here the pointer is empty because of the problem.
MyClassA a1 = container;
container = b;
MyClassB = container;
}