Skip to content

Commit 5879b71

Browse files
committed
opt(main): 优化Module::add(),防止同一个对象被多次add()到不同的父Module上
1 parent 69d0aa8 commit 5879b71

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

modules/main/module.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,19 +52,26 @@ bool Module::add(Module *child, bool required)
5252
return false;
5353
}
5454

55+
//! 防止child被重复添加到多个Module上
56+
if (child->parent_ != nullptr) {
57+
LogWarn("module %s can't add %s, it has parent", name_.c_str(), child->name_.c_str());
58+
return false;
59+
}
60+
61+
//! 检查名称有没有重复的
5562
auto iter = std::find_if(children_.begin(), children_.end(),
5663
[child] (const ModuleItem &item) {
57-
return item.module_ptr == child ||
58-
item.module_ptr->name() == child->name();
64+
return item.module_ptr->name() == child->name();
5965
}
6066
);
6167
if (iter != children_.end()) {
62-
LogWarn("module %s is already exist or name duplicated.", child->name().c_str());
68+
LogWarn("module %s can't add %s, name dupicated.", name_.c_str(), child->name().c_str());
6369
return false;
6470
}
6571

6672
children_.emplace_back(ModuleItem{ child, required });
6773
child->vars_.setParent(&vars_);
74+
child->parent_ = this;
6875

6976
return true;
7077
}

modules/main/module.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ class Module {
141141
std::vector<ModuleItem> children_;
142142
State state_ = State::kNone;
143143

144+
Module *parent_ = nullptr;
144145
util::Variables vars_;
145146
};
146147

0 commit comments

Comments
 (0)