Vik*_*cha 5 c++ stdmap stdstring
使用std::map时析构函数是否会在元素上调用std::map::clear?
我尝试调试,std::map<string,string>但是看不到std::string析构函数被调用。任何人都可以帮助我理解吗?
文档指出它被调用了,但是我没有注意到。
文档是对的,它确实被调用了。
销毁将通过方法完成std::allocator<T>::deallocate()。在调试器中跟踪它。
http://www.cplusplus.com/reference/std/memory/allocator/
析构函数确实会被调用。这是一个示例说明:
#include <iostream>
#include <map>
class A
{
public:
A() { std::cout << "Constructor " << this << std::endl; }
A(const A& other) { std::cout << "Copy Constructor " << this << std::endl; }
~A() { std::cout << "Destructor " << this <<std::endl; }
};
int main()
{
std::map<std::string, A> mp;
A a;
mp.insert(std::pair<std::string, A>("hello", a));
mp.clear();
std::cout << "Ending" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这将报告类似于以下内容的输出:
Constructor 0xbf8ba47a
Copy Constructor 0xbf8ba484
Copy Constructor 0xbf8ba48c
Copy Constructor 0x950f034
Destructor 0xbf8ba48c
Destructor 0xbf8ba484
Destructor 0x950f034
Ending
Destructor 0xbf8ba47a
Run Code Online (Sandbox Code Playgroud)
因此,您可以看到通过调用clear函数来调用析构函数。