C++ 使用 .reset() 释放一个拥有唯一所有权的 boost::shared_ptr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/156373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using .reset() to free a boost::shared_ptr with sole ownership
提问by Zack The Human
I'm storing an object (TTF_Font
) in a shared_ptr
that is provided to me from a third-party API. I cannot use new or delete on the object, so the shared_ptr
is also provided a "freeing" functor.
我将一个对象 ( TTF_Font
)存储在shared_ptr
从第三方 API 提供给我的 a 中。我不能在对象上使用 new 或 delete,因此shared_ptr
还提供了一个“释放”函子。
// Functor
struct CloseFont
{
void operator()(TTF_Font* font) const
{
if(font != NULL) {
TTF_CloseFont(font);
}
}
};
boost::shared_ptr<TTF_Font> screenFont;
screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() );
If, later, I need to explicitly free this object is it correct to do this:
如果稍后我需要明确地释放这个对象,这样做是否正确:
screenFont.reset();
And then let screenFont
(the actual shared_ptr
object) be destroyed naturally?
然后让screenFont
(实际shared_ptr
对象)自然销毁?
回答by Michael Burr
shared_ptr<>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared_ptr<> will be freed.
shared_ptr<>::reset() 会将引用计数减一。如果这导致计数降为零,则 shared_ptr<> 指向的资源将被释放。
So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen.
所以我认为你的答案是,是的,这会奏效。或者您可以简单地让 screenFont 变量由于超出范围或其他原因而被破坏,如果这就是即将发生的事情。
To be clear, the normal usage of shared_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr<> would be naturally destructed.
需要说明的是,shared_ptr<>的正常用法是你让它自然销毁,当它自然降为零时,它会处理refcount并释放资源。仅当您需要在 shared_ptr<> 自然销毁之前释放共享资源的特定实例时才需要 reset()。
回答by Chris Jester-Young
Mike B's answered your question, so I'll just comment on your code. If TTF_OpenFont
doesn't return null, or if TTF_CloseFont
can handle nulls harmlessly, you don't need a CloseFont
class at all, just use &TTF_CloseFont
.
Mike B 回答了你的问题,所以我只会评论你的代码。如果TTF_OpenFont
不返回空值,或者TTF_CloseFont
可以无害地处理空值,则根本不需要CloseFont
类,只需使用&TTF_CloseFont
.