c++ - VC++中_com_ptr_t赋值

标签 c++ visual-c++

我有以下代码:

int _tmain(int argc, _TCHAR* argv[])
{
    // Initialize COM.
    HRESULT hr = CoInitialize(NULL);

    // Create the interface pointer.
    ICalculatorPtr pICalc(__uuidof(ManagedClass));

    long lResult = 0;

    // Call the Add method.
    pICalc->Add(5, 10, &lResult);

    wprintf(L"The result is %d\n", lResult);


    // Uninitialize COM.
    CoUninitialize();
    return 0;
}

我想首先将 pICalc 声明为全局变量,然后在 _tmain 函数内分配一些值。我怎样才能做到这一点?我想,像这样:

ICalculatorPtr pICalc;
//...
int _tmain(int argc, _TCHAR* argv[])
{
    //...
    pICalc = __uuidof(ManagedClass);
}

但这会抛出:

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const _GUID' (or there is no acceptable conversion)

提前致谢。

解决方案:

ICalculatorPtr pICalc = NULL;
//...
int _tmain(int argc, _TCHAR* argv[])
{
    //...
    pICalc = new ICalculatorPtr(__uuidof(ManagedClass));
}

最佳答案

您建议的解决方案会泄漏内存。做到这一点

ICalculatorPtr pICalc;
pICalc.CreateInstance(__uuidof(ManagedClass));

关于c++ - VC++中_com_ptr_t赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849884/

相关文章:

Windows Phone 8.1 的 C++11/14 特性

c++ - Protobuf类型和变体数组类型

c++ - 是否可以在 C++ 中创建可重新定义的命名空间别名?

visual-studio-2010 - 在 VS2010 中调试 Win32 MFC 应用程序时显示控制台窗口

string - BSTR 和字符串

windows - 如何将 UAC 盾牌图标添加到标准消息框?

c++ - 处理大型 TIFF 图像 C++/Magick/libtiff

c++ - 模板函数调用歧义错误

c++ - 尝试禁用无参数成员函数时,SFINAE 无法在 decltype() 内工作

c++ - const char [22 ]' to ' LPCWSTR'