是否允许STL在容器的元素上多次调用析构函数

时间:2011-09-07 09:12:18

标签: stl destructor

基本上我有一个奇怪的问题,我有一个从计数器结构继承的结构节点。在计数器结构中,我进行了这项检查,以“确定”只在已分配的内存上调用析构函数,并且只调用一次。

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

1 个答案:

答案 0 :(得分:3)

check是静态的,这意味着它由类的所有实例共享。由于您希望check成为普通的班级成员,因此您应该删除static关键字。