自动内存管理
class CObject {
public:
CObject(std::string sName, CObject* opParent = nullptr) : msName(sName), mopParent(opParent) {
if (mopParent != nullptr) {
mopParent->mvAddChindObject(this);
}
}
~CObject() {
if (mopParent != nullptr) {
mopParent->mvRemoveChindObject(this);
}
auto lst_chind_obj_temp = mlstChindObject;
for (CObject* op_chind : lst_chind_obj_temp) {
delete op_chind;
}
mlstChindObject.clear();
std::cout << "delete object, name : " << msName << std::endl;
}
void mvAddChindObject(CObject* opChild) {
if (opChild == nullptr) {
return;
}
if (auto itor = std::find(mlstChindObject.begin(), mlstChindObject.end(), opChild); itor == mlstChindObject.end()) {
std::cout << msName << " add chind object " << opChild->msName << std::endl;
mlstChindObject.push_back(opChild);
}
}
void mvRemoveChindObject(CObject* opChild) {
if (opChild == nullptr) {
return;
}
if (auto itor = std::find(mlstChindObject.begin(), mlstChindObject.end(), opChild); itor != mlstChindObject.end()) {
std::cout << msName << " remove chind object " << opChild->msName << std::endl;
mlstChindObject.remove(opChild);
}
}
private:
std::string msName;
CObject* mopParent;
std::list<CObject*> mlstChindObject;
};
void mvTest() {
CObject parent("Parent", nullptr);
CObject* op_parent_1 = new CObject("Parent1", &parent);
CObject* op_child_1_1 = new CObject("Chind_1_1", op_parent_1);
CObject* op_child_1_2 = new CObject("Chind_1_2", op_parent_1);
CObject* op_child_1_3 = new CObject("Chind_1_3", op_parent_1);
CObject* op_child_1_4 = new CObject("Chind_1_4", op_parent_1);
CObject* op_parent_2 = new CObject("Parent2", &parent);
CObject* op_child_2_1 = new CObject("Chind_2_1", op_parent_2);
CObject* op_child_2_2 = new CObject("Chind_2_2", op_parent_2);
CObject* op_child_2_3 = new CObject("Chind_2_3", op_parent_2);
CObject* op_child_2_4 = new CObject("Chind_2_4", op_parent_2);
}
|