静态 CComPtr 变量
在应用程序中使用静态 CComPtr 成员变量是不是一个坏主意? 由于我们无法控制静态变量的销毁,并且它可能在 CoUninitialze 之后发生。
Is it bad idea to have static CComPtr member variables in an application.
Since we cannt control destruction of static variable and it can happen after CoUninitialze .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您采取适当的预防措施,那么使用
CComPtr
作为静态成员本质上并不是邪恶的。我所说的“适当的预防措施”是指您应该考虑:
使用前;
CComPtr::Release
是在您的班级自己的FinalRelease
中调用当实例计数达到零时的方法。Provided you take the appropriate precautions, then using a
CComPtr
as a static member is not inherently evil.By "appropriate precautions", I mean you should consider:
before usage;
CComPtr::Release
is called in your class' ownFinalRelease
method when the instance count reaches zero.无论如何,这是一个坏主意
it is a bad idea anyway
正如谢尔盖在评论中所说,我认为这很糟糕。静态对象的析构函数在 main 终止后调用,如 C++03 标准第 3.6.3 节中所述:
如下演示: http://www.geeksforgeeks.org/static-objects-destroyed/ 。
但是 CoUninitialize 其中在 Main 终止之前调用清理主线程上的 COM 库。 CoUninitialize 将清理所有剩余资源,如 msdn 文档中所述。我们应该在调用 CoUninitialize 之前调用 COM 对象的 Release 方法,因为之后它们将不再存在,因此我们应该确保对 CComPtr 析构函数的调用发生在调用 CoUninitialize 之前。因此,不应将 CComPtr 设为静态。
As Sergey said in his comment, I think it is bad. Destructors of static objects are called after main terminates as explained in section§ 3.6.3 of the C++03 standard:
and as demoed here: http://www.geeksforgeeks.org/static-objects-destroyed/.
But CoUninitialize which cleans the COM library on the main thread is called before Main terminates. CoUninitialize will clean up all remaining resources as explained in the msdn documentation. We should call the Release method of COM objects before CoUninitialize is called because they won't exist anymore after and therefore we should make sure that calls to CComPtr destructor happen before CoUninitialize is called. Therefore a CComPtr should not be made static.