讓我們看一下表示子節點樹的數據結構(Node)的例子。每個對象的子節點集存儲在地圖中>shared_ptr垃圾桶的分配是否可以使用`this`指針
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實例)無意中破壞「這個」點頭e自上次參考文獻剛剛離開? (因此在spChild賦值之後調用其他方法是危險的)。我在這裏有潛在的錯誤嗎?
我認爲解決方法是簡單地在方法調用的頂部添加這一行:
NodePtr spChildRef = spChild; // maintain a reference to the caller's original node during the scope of the method
的思考?
如果它確實是垃圾,那麼它會是最奇怪的,也許最難檢測到'刪除這個;'我會遇到。 –
@Mat - spNode將是這種特殊情況下的根節點,其refcounf爲1. – selbie