如何使用模板中的放置删除/新建来重置类?

发布于 2024-07-12 11:36:56 字数 605 浏览 4 评论 0原文

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

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,我仍在使用 vs 2003。

I have a pool manager template class. When a class object gets added back to the pool manager I would like to reset it back to it's initial state. I would like to call the placment destructor and placment constructor on it so it gets fully reset for the next time it is given out by the pool manager. I've tried many ways to get this to work but I'm stumped. Here is an example of what I have tried.

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
}

I've tried a bunch of different syntaxes and none seem to work. The code itself is cross platform so should compile using gcc ( under mingw or linux or mac ) and for windows I'm still using vs 2003.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小瓶盖 2024-07-19 11:36:56

怎么样:

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...
}

How about:

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...
}
萌酱 2024-07-19 11:36:56

Boost 有一个 Pool 库。 使用他们的而不是编写自己的可能更容易。

Boost has a Pool library. It might be easier to just use theirs instead of writing your own.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文