The difference between a pointer to a pointer and a pointer to a pointer (C ++)

I have COM code that uses interface pointers. The original author of the code implemented functions that return an interface pointer as follows:

HRESULT Query ( IN BSTR sQuery, OUT IEnumWbemClassObject* &pEnumerator ); // (1) 

instead of traditional

 HRESULT Query ( IN BSTR sQuery, OUT IEnumWbemClassObject** ppEnumerator ); // (2) 

Function (1) is called like this:

 hRes = Query ( sQuery, pEnumerator ); // (3) 

which definitely looks wrong, but it works great. I am not sure if I am simply collecting this line because the out parameter is not a pointer to the output variable or because there is something wrong with this approach.

Is there any advantage to using a pointer-pointer instead of a pointer to a pointer for parameters?

+4
source share
4 answers

The first example is a pointer reference, i.e. reference to type IEnumWbemClassObject* :

 HRESULT Query ( IN BSTR sQuery, OUT IEnumWbemClassObject* &pEnumerator ); 

Therefore, if pEnumerator declared as IEnumWbemClassObject* (which I assume is), you do not need to explicitly pass the address of pEnumerator function or dereference the variable inside the function in order to change where pEnumerator points (which would otherwise be required with the IEnumWbemClassObject** argument IEnumWbemClassObject** )

A link to a pointer has the same behavior as a link to any other type, just think of the above example as a pointer to a link to a pointer and not a to a link. There is no such thing as a pointer to a link.

+3
source

The benefits are the same as using links instead of pointers:

  • Simplicity
  • links cannot be null, so assigning a link in Query will not result in an access violation

Please note that the original description was in error: IEnumWbemClassObject* & - link to a pointer, not a pointer to a link.

+4
source

It is better to think of Type & foo * as a reference to a pointer, and not vice versa, since this does not mean that you can change the link through a pointer or other similar C ++ -breaking ideas. It also makes this function call a little easier to believe, since it simply passes something else by reference, does not require dereferencing or special characters.

+2
source

Its because the pointer and the link appear identically in a regular C ++ implementation (this implementation detail, however, is not part of the standard. Also, a link to a pointer, not a pointer to a link, you are not allowed to create a pointer to the link at all.

+1
source

Source: https://habr.com/ru/post/1385241/


All Articles