为什么shared_ptr没有虚拟解析器? (我怎么能解决这个问题?) [英] Why doesn't shared_ptr have a virtual descructor? (and how can I get around this?)
问题描述
我想创建一个特殊版本的 shared_ptr
,在创建或销毁时执行特定操作,但我的计划似乎被 shared_ptr
的析构函数是非虚拟的,意味着当我重写它,我的指针永远不会被清除,当他们的最后一个实例被销毁。
I wanted to make a special version of shared_ptr
that would perform specific operations when it was created or destroyed, but my plans appear to be foiled by the realization that shared_ptr
's destructor is non virtual, meaning when I override it, my pointers never get cleaned up when the last instance of them are destroyed.
想到的唯一替代方法是将这个行为构建到我想要与我的假设自定义 shared_ptr
一起使用的每个类中,这是不可行的或在某些情况下可能)。
The only alternative that comes to mind is to build in this behavior into every class that I want to use with my hypothetical custom shared_ptr
, and that's not feasible (or possible in some cases).
编辑:
我想要的原因是因为我想在lua中使用一些类作为userdata对象,我想要我的每个对象,我使用这种方式有一个fenv表是唯一的,将被清理时,对该对象的所有引用已删除。我计划使用指针的地址作为他们的钥匙到一个表中保存fenv表。
The reason I want this is because I want to use some classes as userdata objects in lua, and I want each one of my objects that I use this way to have a fenv table unique to it that will be cleaned up when all references to the object have been removed. I plan on using the address of the pointer as they key into a table that holds the fenv table.
让我说我有一个小部件,可以有其他小部件作为孩子。我在Lua中创建两个小部件,然后将其中一个设置为另一个的子对象,并删除对子小部件的所有lua引用(事实上,它是一个使用C ++处理的子代)。 GC现在可以随时运行并删除孩子。我不一定希望孩子有它的析构函数运行,所以我想做一个shared_ptr。这样,C ++对象仍然可以使用它,在Lua清理它。如果我已经为它的fenv分配了值或函数,我仍然希望能够访问它们。
Lets say I have a widget that can have other widgets as children. I create two widgets in Lua, then set one as the child of the other and remove all lua references to the child widget (the fact that it's a child is handled in C++). The GC can now run at any time and remove the child. I don't necessarily want the child to have it's destructor run though, so I want to make it a shared_ptr. That way, C++ objects can still use it after Lua has cleaned it up. If I've assigned values or functions to it's fenv I still want to be able to access them. Only when the final reference to my child widget is removed do I want the fenv tabled to be removed totally.
推荐答案
它已经有了这种能力建立在不需要让人们做危险的事情,如从中得到:
It already has this ability built in without the need to let people do dangerous things like derive from it:
#include <boost/shared_ptr.hpp>
#include <iostream>
/*
* Done as a function for simplicity.
* But this can be done in so many ways
*/
void MyCleanup(int* x)
{
std::cout << "DONE\n";
delete x;
}
int main()
{
boost::shared_ptr<int> x(new int(5), MyCleanup);
}
导出问题:
Problem with deriving:
Just off the top of my head.
class X: public shared_ptr<int> { /* STUFF. With a special destructor. */ };
int main()
{
/* what happens now? Similar to slicing but not quite */
X data1(new int(5));
shared_ptr<int> data2;
shared_ptr<int> data3(data);
data2 = data1;
}
这篇关于为什么shared_ptr没有虚拟解析器? (我怎么能解决这个问题?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!