Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error C2275 while creating a COM smart-pointer within "if" statement

Why can't i

if (IUnknownPtr p = anotherComPtr) {} //error C2275: 'IUnknownPtr' : illegal use of this type as an expression

while i can

if (int* a = anotherPointer) {}

IUnknownPtr is defined throught _COM_SMARTPTR_TYPEDEF(IUnknown, __uuidof(IUnknown)) (like any others smart pointers i use)

How can i create a com smartptr within if statement and verify is it valid or not? Thank you.

I use VS 2008

p.s. This is not about is it good way of coding or not, it's about error C2275.

like image 668
fogbit Avatar asked Nov 14 '22 10:11

fogbit


1 Answers

I can't reproduce your compiler error in vs2008 in the small program below. There is likely to be something different in your include files, preprocessor definitions or compiler options which is giving you different behaviour.

Can you declare a simple variable of type IUnknownPtr outside an if statement?

Can you create a new project using the code below without the error?

Does either of the following compile OK?

if (NULL == (IUnknownPtr ptr = someOtherPtr)) {
}

IUnknownPtr foo;
bool b(foo);

The error suggests the compiler can see a definition of IUnknownPtr but can't interpret the result of the assignment of an IUnknownPtr as a bool.

operator = should return IUnknownPtr& (the object that's been assigned to). _com_ptr_t defines operator bool(). Are your _COM_SMARTPTR_TYPEDEF generating references to _com_ptr_t or some other type? You can easily find out by temporarily dumping out the preprocessor output (properties/C++/preprocessor/preprocess to a file)

#include <comdef.h>

int main(int argc, char* argv[])
{
    IUnknownPtr foo;
    IUnknown* foo2 = NULL;

    if (IUnknownPtr foo3 = foo) {
        // do something
    }

    if (IUnknownPtr foo4 = foo2) {
        // do something
    }

    return 0;
}
like image 114
persiflage Avatar answered Dec 06 '22 15:12

persiflage