C++ 在COM中测试CComPtr是否为null

C++ 在COM中测试CComPtr是否为null,c++,visual-studio-2013,com,C++,Visual Studio 2013,Com,我有一个关于COM智能指针类的用法的问题CComPtr。我遵循的是中的一个示例,代码似乎没有在CComPtr上调用CoCreateInstance()(它只是在赋值之前声明它) 所以我写了一个这样的测试程序: #include "stdafx.h" #include "atlbase.h" #include <iostream> int _tmain(int argc, _TCHAR* argv[]) { CComPtr<int> myint = nullptr

我有一个关于COM智能指针类的用法的问题
CComPtr
。我遵循的是中的一个示例,代码似乎没有在
CComPtr
上调用
CoCreateInstance()
(它只是在赋值之前声明它)

所以我写了一个这样的测试程序:

#include "stdafx.h"
#include "atlbase.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    CComPtr<int> myint = nullptr;
    if (myint == nullptr) {
        std::cout << "yes" << std::endl;
    }
    return 0;
}
#包括“stdafx.h”
#包括“atlbase.h”
#包括
int _tmain(int argc,_TCHAR*argv[]
{
CComPtr myint=nullptr;
if(myint==nullptr){
标准::cout
为什么将nullptr分配给CComPtr对象是非法的

不是。正如Hans指出的,
CComPtr
只能与COM接口一起使用,
int
不是兼容类型。这就是编译器错误告诉您的:

error C2227: left of '->Release' must point to class/struct/union/generic type type is 'int *'

int-tmain(int-argc,_-TCHAR*argv[]
{
CComPtr myUnk=nullptr;
如果(myUnk){//调用myUnk.operator IUnknown*()。。。

std::cout-CComPtr是COM接口指针的智能指针包装器。从IUnknown派生的类型。使用int没有任何意义。您会得到编译错误,因为int没有Release()方法。由CComPtr在其析构函数(智能部分)中自动调用。但是如何检查CComPtr是否拥有任何对象?只是一个“如果”(ccomPtr)“你会做这个把戏吗?你已经知道怎么做了,这是你没有做错的一件事。”。 error C2227: left of '->Release' must point to class/struct/union/generic type type is 'int *'
int _tmain(int argc, _TCHAR* argv[])
{
    CComPtr<IUnknown> myUnk = nullptr;
    if (!myUnk) { // calls myUnk.operator!() ...
        std::cout << "null" << std::endl;
    else
        std::cout << "not null" << std::endl;
    }
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    CComPtr<IUnknown> myUnk = nullptr;
    if (myUnk) { // calls myUnk.operator IUnknown*() ...
        std::cout << "not null" << std::endl;
    else
        std::cout << "null" << std::endl;
    }
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    CComPtr<IUnknown> myUnk = nullptr;
    if (myUnk == nullptr) { // calls myUnk.operator==(IUnknown*) ...
        std::cout << "null" << std::endl;
    else
        std::cout << "not null" << std::endl;
    }
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    CComPtr<IUnknown> myUnk = nullptr;
    if (myUnk.IsEqualObject(nullptr)) {
        std::cout << "null" << std::endl;
    else
        std::cout << "not null" << std::endl;
    }
    return 0;
}