STL 是否允许对容器的元素多次调用析构函数
基本上我有一个奇怪的问题,我有一个继承自计数器结构的节点结构。在计数器结构中,我进行了此检查以“确保”仅在分配的内存上调用析构函数并且仅调用一次。
static atomic < int > check;
counter()
{
check=42;
//...
}
~counter()
{
if (check!=42)
{
cout<<"ouch"<< typeid(T).name()<<" "<< check<<" "<< objects_created<< endl;
sleep(1);
assert(0);
}
check=84;
//...
}
当用 g++4.6 编译时它会崩溃
3 0x00007ffff65ec7a4 in counter<Node>::~counter (this=0x614c60,
__in_chrg=<value optimized out>)
at /home...
4 0x00007ffff65e7a4d in Node::~Node (this=0x614c60,
__in_chrg=<value optimized out>)
at /home...
5 0x00007ffff6603cf2 in std::_Destroy<Node> (__pointer=0x614c60)
at /usr/include/c++/4.6/bits/stl_construct.h:92
6 0x00007ffff6600004 in std::_Destroy_aux<false>::__destroy<Node*> (
__first=0x614c60, __last=0x614d40)
at /usr/include/c++/4.6/bits/stl_construct.h:102
7 0x00007ffff65fa003 in std::_Destroy<Node*> (__first=0x614c60,
__last=0x614d40) at /usr/include/c++/4.6/bits/stl_construct.h:125
8 0x00007ffff65f2a4f in std::_Destroy<Node*, Node> (__first=0x614c60,
__last=0x614d40) at /usr/include/c++/4.6/bits/stl_construct.h:151
9 0x00007ffff65ecfb2 in std::vector < Node, std::allocator < Node>
>::~vector (
this=0x7ffff68329f8, __in_chrg= < value optimized out>)
at /usr/include/c++/4.6/bits/stl_vector.h:348
Basically I have a strange problem, I have a struct Node that inherits from counter struct. And in the counter struct I have this check to make "sure" that Destructor is called only on allocated memory and that it is called only once.
static atomic < int > check;
counter()
{
check=42;
//...
}
~counter()
{
if (check!=42)
{
cout<<"ouch"<< typeid(T).name()<<" "<< check<<" "<< objects_created<< endl;
sleep(1);
assert(0);
}
check=84;
//...
}
and it breaks when compiled with g++4.6
3 0x00007ffff65ec7a4 in counter<Node>::~counter (this=0x614c60,
__in_chrg=<value optimized out>)
at /home...
4 0x00007ffff65e7a4d in Node::~Node (this=0x614c60,
__in_chrg=<value optimized out>)
at /home...
5 0x00007ffff6603cf2 in std::_Destroy<Node> (__pointer=0x614c60)
at /usr/include/c++/4.6/bits/stl_construct.h:92
6 0x00007ffff6600004 in std::_Destroy_aux<false>::__destroy<Node*> (
__first=0x614c60, __last=0x614d40)
at /usr/include/c++/4.6/bits/stl_construct.h:102
7 0x00007ffff65fa003 in std::_Destroy<Node*> (__first=0x614c60,
__last=0x614d40) at /usr/include/c++/4.6/bits/stl_construct.h:125
8 0x00007ffff65f2a4f in std::_Destroy<Node*, Node> (__first=0x614c60,
__last=0x614d40) at /usr/include/c++/4.6/bits/stl_construct.h:151
9 0x00007ffff65ecfb2 in std::vector < Node, std::allocator < Node>
>::~vector (
this=0x7ffff68329f8, __in_chrg= < value optimized out>)
at /usr/include/c++/4.6/bits/stl_vector.h:348
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
check
是静态的,这意味着它由该类的所有实例共享。由于您希望check
成为普通类成员,因此应该删除static
关键字。check
is static, which means that it is shared by all instances of the class. Since you wantcheck
to be a normal class member, you should remove thestatic
keyword.