我試圖找出爲什麼我的Tag類的析構函數被調用C++參考變量的作用域問題
map<string, Tag>* TestLoader::loadCompoundTag()
{
map<string, Tag>* compound = new map<string, Tag>();
//Create locally scoped variable
Tag tag;
string tagName;
do
{
loadTag(tag, tagName);
//Copies variable into map
compound->insert(std::pair<string, Tag>(tagName, tag));
//Tag destructor is called before debugger breaks on this line
} while (tag.type != TAG_End);
return compound;
}
void TestLoader::loadTag(Tag& tag, string& name)
{
tag.i = 0;
name = string("Test");
}
誰能給我任何的想法,爲什麼析構函數被調用呢?在循環的範圍中沒有定義任何變量,一個是在循環外創建的,另一個是在函數內部創建的。謝謝!
爲什麼不'std :: shared_ptr標籤(新標籤());'? –
jweyrich
我想避免動態創建它,因爲它只是要被複制到地圖中,當我有點困惑時,爲什麼正確的值在地圖中結束,但在循環結束之前調用析構函數 – Istinra
您確定被破壞的'Tag'對象是'tag',而不是'std :: pair(tagName,tag)'中的副本。 –
updogliu