I have a bit of COM code that uses interface pointers. The original author of the code implemented functions that return an interface pointer like this:
HRESULT Query ( IN BSTR sQuery, OUT IEnumWbemClassObject* &pEnumerator ); // (1)
instead of the traditional
HRESULT Query ( IN BSTR sQuery, OUT IEnumWbemClassObject** ppEnumerator ); // (2)
The function (1) is called like this:
hRes = Query ( sQuery, pEnumerator ); // (3)
which definitely looks wrong but it works fine. I'm not sure if I'm just picking up this line because the out parameter is not a pointer to the output variable or because there's something wrong with this approach.
Is there an advantage to using a reference-to-pointer instead of a pointer-to-pointer for out parameters?
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.
Memory Address: A pointer has its own memory address and size on the stack, whereas a reference shares the same memory address with the original variable but also takes up some space on the stack.
References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
The first example is that of a reference to a pointer, ie. a reference to a type IEnumWbemClassObject*
:
HRESULT Query ( IN BSTR sQuery, OUT IEnumWbemClassObject* &pEnumerator );
Therefore if pEnumerator
is declared as a IEnumWbemClassObject*
(which I'm assuming it is), you don't need to explicitly pass the address of pEnumerator
to the function or dereference the variable inside the function in order to change where pEnumerator
points (which would otherwise be required with an argument of IEnumWbemClassObject**
).
A reference to a pointer has the same behaviour as a reference to any other type, just think of the above example as being a "reference to a pointer" and not a "pointer to a reference." There's no such thing as a pointer to a reference.
The advantages are the same as any use of references instead of pointers:
Query
won't cause an access violationNote the original description was in error: IEnumWbemClassObject* &
is a reference to a pointer, not a pointer to a reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With