auto_handle仍然是建议的处理方式吗? [英] Is auto_handle still the suggested method for determanistic disposal of handles?

查看:156
本文介绍了auto_handle仍然是建议的处理方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个同事在周末碰到了一篇有关codeproject的文章,其中描述了

A colleague of mine came across an article on codeproject over the weekend which describes the use of the auto_handle method. Given that the article was written in 2006, is that still the right way to handle deterministic disposal for things like file handles?

我们倾向于显式刷新并关闭文件句柄,然后删除指针并将它们清空以确保GC没有借口不收集它们(是的,我们知道我们是超级偏执狂).使用类似auto_handle的东西看起来可以帮助我们更加懒惰(并且在安全的情况下我们喜欢懒惰),但是我们现在不想开始使用它被认为是不好的做法,并且/或者我们可以使用更好的东西

We've tended to explicitly flush and close file handles and then delete the pointers and null them to be certain the GC has no excuse not to collect them (yes, we know we're super-paranoid). Using something like auto_handle looks like it could help us be more lazy (and we like being lazy when it's safe to do so) but we don't want to start using it's considered bad practice these days and/or there's something better we can use.

推荐答案

C ++/CLI自2005年发行以来没有变化,因此没有理由假设发生了任何新变化.与2005年有效的建议相同,auto_handle不是自动删除对象的最佳方法.首先,您应该考虑堆栈语义,它涵盖了绝大多数情况.编译器自动生成try/finally块和 delete 调用(即放置对象),相当于C# using 语句,减去代码.链接中给出的示例是这样完成的:

C++/CLI hasn't changed since the 2005 release, so no reason to assume anything new happened. Same advice as was valid back in 2005, auto_handle is not the best way to auto-delete objects. You should consider stack semantics first, it covers the vast majority of cases. The compiler auto-generates the try/finally blocks and the delete call (i.e. disposes the object), equivalent to the C# using statement, minus the code. The example given in the link is done like this:

void Demo1A()
{
    StreamWriter sw("c:\\temp\\test.txt");
    sw.WriteLine("This is a line of text");
}   // <=== Compiler auto-generates the StreamWriter::Dispose call here

请注意对象声明中缺少的^帽子.

Note the missing ^ hat on the object declaration.

do 认为,这与垃圾收集器完全无关,仅与确定性的资源清除有关.还要注意,将局部变量设置为nullptr是非常不合适的,它可以不必要地延长引用的使用寿命,使其超出其实际使用范围.抖动优化器将删除分配.

And do consider that this has nothing at all to do with the garbage collector, only with deterministic resource cleanup. Also note that setting local variables to nullptr is very inappropriate, it can extend the lifetime of a reference beyond its actual use unnecessarily. The jitter optimizer removes the assignments.

这篇关于auto_handle仍然是建议的处理方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆