我目前正在学习智能指针,尽量避免使用原始指针。
我有一个带有共享点的 vector
std::vector<std::shared_ptr<View>> mChildren;
和一个添加和删除方法
void View::AddChild(std::shared_ptr<View> view) {
mChildren.push_back(view);
}
void View::RemoveChild(std::shared_ptr<View> view) {
auto removal = std::remove(mChildren.begin(), mChildren.end(), view);
mChildren.erase(removal, mChildren.end());
}
现在在我的代码的另一部分我有一张 map
std::map<std::weak_ptr<ModelGem>,std::unique_ptr<ViewGem>,std::owner_less<std::weak_ptr<ModelGem>>> mViews;
现在,当我尝试像这样从 map 中删除元素时:
for (auto iterator = mViews.begin(); iterator != mViews.end();)
{
if (iterator->first.expired())
{
RemoveChild(iterator->second.get());
iterator = mViews.erase(iterator);
}
else
{
iterator++;
}
}
现在问题出在这里:iterator->second.get()
它告诉我它不能将类型指针的右值转换为共享指针。
但是,如果我使用原始指针而不是共享指针,这根本不是问题。
所以,我想知道在这种情况下是只使用原始指针更好还是我可以使用共享指针来解决这个问题?
最佳答案
So, I am wondering if in this case it would be better to just use raw pointers or can I work around this with shared pointers?
在大多数情况下,只有一种右指针类型可供使用。并不是说一个比另一个好。只有一种正确的方法。
map 上有一个 unique_ptr<ViewGem>
.这意味着它拥有完全的所有权并且不与任何其他数据结构共享。所以不可能在 vector<shared_ptr...>
中有相同的对象而不会导致未定义的行为。你必须决定哪个 ds 拥有所有权,
- 如果 map 拥有完整所有权,请使用
unique_ptr
在 map 中,在 vector 中的原始 ptr - 如果 vector 有所有权,使用
unique_ptr
在 map 中的 vector 和原始 ptr 中。 - 如果所有权类似于 ds 拥有并且对象只有在从 map 和 vector 中删除时才应销毁,则使用
shared_ptr
在两者中。
关于c++ - 从 vector 或 map 中删除共享指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52916463/