让我们以表示子节点树的数据结构(节点)为例。每个对象的子节点集存储在 map 中>
class Node;
typedef std::shared_ptr<Node> NodePtr;
class Node
{
std::map<const std::string, NodePtr> _childNodes;
void SomeOtherMethod();
public:
bool GetChildByKeyName(/*In*/ const std::string& key, /*Out*/ NodePtr& spChild)
{
bool result = false;
auto itor = _childNodes.find(key);
if (itor != _childNodes.end())
{
spChild = itor->second;
result = true;
SomeOtherMethod();
}
return result;
}
};
以及用户通常会调用的以下代码示例。
NodePtr spNode, spChildNode;
bool result;
...
result = spNode->GetChildByKeyName(strChildKeyName, spChildNode);
到目前为止一切顺利。
我想到调用者可能会遍历树而不必为树的每个深度处理额外的变量
NodePtr spNode;
bool result;
result = spNode->GetChildItem(strChildKeyName, spNode);
if (result)
spNode->GetChildItem(strSubKeyName, spNode);
在上述情况下,如果 spNode 是对象的最终剩余引用,那么我担心 GetChildItem 方法中的这段代码:
spChild = itor->second;
result = true;
SomeOtherMethod();
spChild 的赋值(实际上是调用者的 spNode 实例)是否在最后一个引用刚刚消失后无意中破坏了“this”节点? (因此在 spChild 分配之后调用其他方法是危险的)。我这里有潜在的错误吗?
我认为解决方法是简单地在方法调用的顶部添加这一行:
NodePtr spChildRef = spChild; // maintain a reference to the caller's original node during the scope of the method
想法?
最佳答案
您是正确的,如果第二个示例中最外层的 spNode 指针是对根项的唯一引用,则 GetChildByKeyName 将替换该引用,从而导致对象破坏(本质上是“删除此”)。
我意识到这可能不是完整的代码,您可能有这样设计的原因,但我个人建议更改接口(interface)以返回找到的子项而不是使用 out 参数。 (您仍然可以通过测试 null 来区分找到 child 的成功与失败。)
不仅实际的查找代码变得更简单了:
NodePtr GetChildByKeyName(/*In*/ const std::string& key)
{
auto itor = _childNodes.find(key);
if (itor != _childNodes.end())
{
SomeOtherMethod();
return itor->second;
}
return nullptr;
}
然后您还可以重用指针指向您的核心内容:
NodePtr spNode;
....
spNode = spNode->GetChildItem(strChildKeyName);
if (spNode)
spNode = spNode->GetChildItem(strSubKeyName);
关于c++ - shared_ptr 的分配是否会破坏 `this` 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22190472/