释放接口指针

Release Interface pointers

本文关键字:指针 接口 释放      更新时间:2023-10-16

在类的析构函数中,我有一些智能指针被声明为类内的成员变量,同时释放这些接口,哪种代码更好:

成员可变

CComQIPtr<IMyInterFace> m_pMyInterface;

构造函数

m_pMyInterface.CreateInstace(CLSID_MyInterface);

在Destructor 中

if(m_pMyInterface)
    m_pMyInterface.Release();

或者应该是

if(m_pMyInterface.p ! = NULL)
    m_pMyInterface.Release();

形成上面哪一个更好,我使用接口指针的方式是否有任何缺陷。当做tom

~CComQIPtr析构函数负责处理一切。您不需要明确发布。然而,如果您想重用变量,您可以执行以下两种操作之一:

  • m_pMyInterface.Release();
  • m_pMyInterface = NULL;(运算符=CComPtr一起工作,可能与CComQIPtr不明确)

NULL检查是不必要的,CComQIPtr::Release方法无论如何都会这样做。

它们是等价的,尽管我真的不喜欢有人仅仅为了它而写书。
此外,Release()调用是不需要的,只需让析构函数处理即可

选择短的。