次の方法で共有


ptr::operator bool

条件式内で com::ptr を使用するための演算子。

operator bool();

戻り値

所有されたオブジェクトが有効な場合は true、それ以外の場合は false です。

解説

所有された COM オブジェクトは、nullptr でない場合に有効です。

この演算子は、実際には _detail_class::_safe_bool に変換されます。bool は整数型に変換できないため bool よりも安全です。

使用例

この例では、プライベート メンバ IXMLDOMDocument オブジェクトをラップするために com::ptr を使用する 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);   
   }
}

DOM Document created.

必要条件

ヘッダー ファイル <msclr\com\ptr.h>

名前空間 msclr::com

参照

概念

ptr Members

ptr::operator!