How do I AddRef() an nsCOMPtr for use as an out param?

129 Views Asked by At

I have a member for my class:

class MyNativeXPCOMObject ... {
    ...
private:
    nsCOMPtr<nsISomeInterface> someInterface_;
    ...
};

I have methods that do this:

NS_IMETHODIMP MyNativeXPCOMObject::GetSomeObject(nsISomeInterface** aSomeInterface) {
    NS_IF_ADDREF(someInterface_);
    *aSomeInterface = someInterface_;
    return NS_OK;
}

But Gecko 9 enforces that you're not allowed to call AddRef() or Release() on nsCOMPtr<>s. So now I'm doing this:

NS_IMETHODIMP MyNativeXPCOMObject::GetSomeObject(nsISomeInterface** aSomeInterface) {
    NS_IF_ADDREF(someInterface_.get());  // <--- Added .get()!
    *aSomeInterface = someInterface_;
    return NS_OK;
}

But directly accessing the raw pointer makes me feel dirty. What is the proper way to AddRef() for out params in getters?

The documentation was not helpful.

1

There are 1 best solutions below

1
On BEST ANSWER

You simply change the instruction order:

*aSomeInterface = someInterface_;
NS_IF_ADDREF(*aSomeInterface);

*aSomeInterface is a raw pointer so you can use NS_IF_ADDREF on it. That's how most Gecko code seems to do it.