代码之家  ›  专栏  ›  技术社区  ›  KPexEA

如何使用Placement delete/new from a template重置类?

  •  1
  • KPexEA  · 技术社区  · 16 年前

    我有一个池管理器模板类。当类对象被添加回池管理器时,我希望将其重置回初始状态。我想在其上调用Place析构函数和Place构造函数,以便在池管理器下一次给出它时完全重置它。我已经尝试了很多方法来让它发挥作用,但是我被难倒了。这是我尝试过的一个例子。

    template <class T>
    void PoolClass<T>::ReleaseToPool(T *obj)
    {
         obj->~T();   //call destructor
    
         obj->T::T(); //call constructor
         //also tried new (obj)T(); //but this doesn't seem to work either
    
         //then misc code to add a pointer to the object
         //to my list of available objects for re-use later
    }
    

    我尝试了很多不同的语法,但似乎都不管用。代码本身是跨平台的,所以应该使用gcc(在mingw或linux或mac下)编译,对于windows,我仍然使用vs2003。

    2 回复  |  直到 16 年前
        1
  •  3
  •   James Eichele Bernard Igiri    16 年前

    template <class T>
    void PoolClass<T>::ReleaseToPool(T *obj)
    {
        obj->~T();                  //call destructor
        obj = new ((void *)obj)T(); //call constructor
    
        // add a pointer to the object to the list...
    }
    
        2
  •  2
  •   Michael Kohne    16 年前

    Boost有一个 Pool 图书馆用他们的而不是自己写可能更容易。