ptr::operator bool

运算符用于 com::ptr 一个条件表达式。

operator bool();

返回值

true ,如果拥有的 COM 对象是有效的;否则 false 。

备注

,如果不是 nullptr,拥有的 COM 对象是有效的。

比 bool 安全的此运算符实际转换为 _detail_class::_safe_bool ,因为它不能转换为整型。

示例

本示例实现使用 com::ptr 包装其私有成员 IXMLDOMDocument 对象的 CLR 类。CreateInstance 成员函数中创建新文档对象之后确定它是否使用 operator bool 是写入控制台的活动和写入,则为。

// comptr_op_bool.cpp
// compile with: /clr /link msxml2.lib
#include <msxml2.h>
#include <msclr\com\ptr.h>

#import <msxml3.dll> raw_interfaces_only

using namespace System;
using namespace System::Runtime::InteropServices;
using namespace msclr;

// a ref class that uses a com::ptr to contain an 
// IXMLDOMDocument object
ref class XmlDocument {
public:
   void CreateInstance(String^ progid) {
      if (!m_ptrDoc) {
         m_ptrDoc.CreateInstance(progid);   
         if (m_ptrDoc) { // uses operator bool
            Console::WriteLine("DOM Document created.");
         }
      }
   }

   // note that the destructor will call the com::ptr destructor
   // and automatically release the reference to the COM object

private:
   com::ptr<IXMLDOMDocument> m_ptrDoc;
};

// use the ref class to handle an XML DOM Document object
int main() {
   try {
      XmlDocument doc;
      // create the instance from a progid string
      doc.CreateInstance("Msxml2.DOMDocument.3.0");
   }
   catch (Exception^ e) {
      Console::WriteLine(e);   
   }
}
  

要求

头文件 <msclr \ COM \ ptr.h>

命名空间 msclr::com

请参见

参考

ptr::operator!

其他资源

PTR成员