Microsoft 对象,Release() 函数返回值?
我很好奇,因为我在 MSDN 上找不到这方面的信息。 我发现 Release()
函数存在于各种 COM 对象中,显然我应该将其用于删除指针。 但我不确定它到底返回什么? 我曾经认为它会返回仍然存在于剩余对象的引用数量,因此类似于:
while( pointer->Release() > 0 );
显然会释放对该指针的所有引用吗?
或者我没有看到什么?
*注意我是从 IDirect3DTexture9::Release() 函数的概念来讨论这个问题的
I'm curious because I couldn't find out about this on MSDN. I've found the Release()
function is present in various COM objects which I'm obviously supposed to use for deleting pointers. But I'm not sure what does it return exactly? I used to think it would return the number of references which still exist to the object remaining, therefore something like:
while( pointer->Release() > 0 );
Would obviously release all references to that pointer?
Or am I not seeing something?
*note I'm talking about this from the concept of the IDirect3DTexture9::Release()
function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了 Mehrdad 所说的之外,Release 的返回值仅用于调试目的。 生产代码应该忽略它。
循环直到 Release() 返回 0 绝对是一个错误 - 你永远不应该释放你不拥有的引用。
In addition to what Mehrdad said, the return value of Release is intended for debugging purposes only. Production code should just ignore it.
Looping until Release() returns 0 is definitely a bug - you should never release references you don't own.
你的理论是正确的。 COM 内存管理基于引用计数。
IUnknown
接口的Release
方法将减少引用计数并返回它。 该函数不会释放引用。 它不知道谁持有该参考。 它只是减少引用计数,直到达到零,然后对象将被销毁。 这是危险的,因为其他人可能仍然持有对它的引用,该引用在对象销毁后将变得无效。因此,您应该只为之前调用的每个
AddRef
调用Release
。Your theory is true. COM memory management is based on reference counting. The
Release
method ofIUnknown
interface will decrement the reference count and return it. That function will not release references. It doesn't know who holds the reference. It just decrements the reference count until it reaches zero and then the object will be destructed. It's dangerous as others might still hold a reference to it that will become invalid after object's destruction.Thus, you should only call
Release
for eachAddRef
you had previously called.Release() 将返回对象的当前引用计数。 但你不应该这样做:
这将使引用计数为零并销毁对象。
通常 Release() 的实现如下所示:
Release() would return the current reference count of the object. But you shouldn't do:
This will make the reference count zero and destroy the object.
Normally Release() implementation would look like this: