我有一组Creature
对象,这些对象是在我的应用程序的一个部分中使用std::make_shared
和创建和拥有的std::shared_ptr
。
我还Creature
使用.World
std::weak_ptr<Creature>
void World::SetSelection(const std::shared_ptr<Creature>& creature) {
selection = creature;
}
std::shared_ptr<Creature> World::GetSelection() const {
return selection.lock();
}
的调用者GetSelection
负责检查指针是否为空。如果是,则表示当前没有选择。
This all works perfectly to my liking: when the selected Creature
dies of natural causes (elsewhere in the application), GetSelection
starts returning a nullptr
again as if nothing was ever selected.
但是在这种情况下,World::selection
成员仍然指向std::shared_ptr
的控制块。这可能很大,因为我std::make_shared
用来创建我的Creature
对象(我意识到该Creature
对象在正确的时间被正确地销毁,但它的内存仍然被分配)。我正在考虑改成GetSelection
这样:
std::shared_ptr<Creature> World::GetSelection() {
const auto ret = selection.lock();
if (!ret)
selection.reset();
return ret;
}
一旦我注意到不再需要它,这就会释放内存。烦人的是,这个版本的GetSelection
cannot be const
。
我的问题:
在这种情况下,哪个版本
GetSelection
被认为是最佳实践?如果在模板代码中发生类似的事情,答案是否会改变,哪里
sizeof(T)
未知并且可能很大?或者在 C++14 中std::make_shared<T[]>
可能涉及到什么?如果第二个版本总是最好的,那么自己不做的理由是
std::weak_ptr<T>::expired
什么lock
?