我创建了一个简单的测试用例,展示了我在正在工作的较大代码库中注意到的奇怪行为。该测试用例如下所示。我依靠STL Map的“[]”运算符,在这样的结构体映射中创建指向结构体的指针。在下面的测试用例中,该行...
TestStruct *thisTestStruct = &testStructMap["test"];
当我使用"[ ]"运算符时,它会给我返回指针,并在映射表中创建一个新条目。我注意到的奇怪之处是,这一行不仅会因为"[ ]"运算符而创建新的映射表条目,还会导致结构体析构函数被额外调用两次。很明显我漏掉了什么 - 非常感谢任何帮助!谢谢!
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct TestStruct;
int main (int argc, char * const argv[]) {
map<string, TestStruct> testStructMap;
std::cout << "Marker One\n";
//why does this line cause "~TestStruct()" to be invoked twice?
TestStruct *thisTestStruct = &testStructMap["test"];
std::cout << "Marker Two\n";
return 0;
}
struct TestStruct{
TestStruct(){
std::cout << "TestStruct Constructor!\n";
}
~TestStruct(){
std::cout << "TestStruct Destructor!\n";
}
};
上面的代码输出以下内容...
/*
Marker One
TestStruct Constructor! //makes sense
TestStruct Destructor! //<---why?
TestStruct Destructor! //<---god why?
Marker Two
TestStruct Destructor! //makes sense
*/
...但我不理解是什么导致了前两次调用 TestStruct 的析构函数?(我认为最后一次析构函数的调用是有意义的,因为 testStructMap 超出了作用域。)