gpt4 book ai didi

C++ 引用变量作用域问题

转载 作者:行者123 更新时间:2023-11-30 02:03:03 27 4
gpt4 key购买 nike

我想弄清楚为什么要调用我的 Tag 类的析构函数

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");
}

谁能告诉我为什么要在那里调用析构函数?没有一个变量在循环范围内定义,一个是在循环外创建的,另一个是在函数内创建的。谢谢!

最佳答案

为了插入您正在创建的临时 map ,

std::pair<string, Tag>(tagName, tag)

在完整表达式结束时它被销毁。

您不必为此担心。如果有必要,可以通过使用 emplace 来避免,但是不要担心。相反,担心函数的结果类型:

为什么需要动态分配的映射

我很确定你不会,也就是说,这是邪恶的过早优化。

因此我强烈建议,关注正确性,让编译器完成其优化工作,然后编写......

map<string, Tag> TestLoader::loadCompoundTag() const
{
map<string, Tag> result;
do
{
Tag tag;
string tagName;
loadTag(tag, tagName);
result->emplace( std::pair<string, Tag>( tagName, tag) );
} while (tag.type != Tag::end);
return result;
}

很可能你甚至不需要让你的编译器优化,为了在这里获得返回值优化,这意味着,显然本地 result 是在由提供的内存区域中构造的调用者,因此不会对函数结果进行复制。

关于C++ 引用变量作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12540140/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com