Question

I am wondering how to define a COM smart pointer in a header file as a class member? Here is what did:

  • In .cpp file, I have:

    long MyClass:MyFun(long &deviceCount)
    {
        RESULT h = CoInitialize(NULL);
        MyComPtr ptr(__uuidof(MyComClass));
    
        if(deviceCount > 0)
            ptr->Connect();
    }
    

But since other functions need to use ptr, I am thinking about changing it to a class member and define it in the header file, something like this:

  • In .h file:

    MyComPtr _ptr;
    
  • then in .cpp file, I have:

    _ptr(__uuidof(MyComClass));
    

But the compile did not go through, it says "term does not evaluate to a function taking 1 argument". I am very confused how I can implement this. Any ideas? Thanks.

EDIT: So to use initilizer list, it shoule be something like this?

MyClass:MyClass() : _ptr(new MyCom)
{
    _ptr(__uuidof(MyComClass));
}
Était-ce utile?

La solution

The initializer list is called at construction time to set variables that would otherwise be const. It's commonly used for const variables, references, etc. I don't actually know COM, but if the smart pointer has similar mechanics to a reference (i.e. once set it cannot be retargeted) then it will have to be initialized at construction time, using an initializer list.

Constructor() : _Ptr(new MyComObject)
{
 // Other constructor stuff here
}

The syntax is probably wrong - as I said, I don't know COM - but this might be helpful?

EDIT:

Assuming you have the following class:

class MyClass
{
public:
    MyClass(); // constructor
    MyComPtr _ptr;
};

Then in your .cpp, define your constructor like this :

MyClass::MyClass() : _ptr(__uuidof(MyComClass)
{
   // rest of constructor code
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top