I'm relatively new to C++ and working on a fairly large C++ project at work. I notice handfuls of functions that take double pointers as parameters for objects that the function will instantiate on the heap. Example:
int someFunc(MyClass** retObj) {
*retObj = new MyClass();
return 0;
}
I'm just not sure why double pointers are always used, in this project, instead of just a single pointer? Is this mostly a semantic cue that it's an out/return parameter, or is there a more technical reason that I'm not seeing?
The double pointer pattern is used so that the newly allocated MyClass
can be passed to the caller. For example
MyClass* pValue;
someFunc(&pValue);
// pValue now contains the newly allocated MyClass
A single pointer is insufficient here because parameters are passed by value in C++. So the modification of the single pointer would only be visible from within someFunc
.
Note: When using C++ you should consider using a reference in this scenario.
int someFunc(MyClass*& retObj) {
retObj = new MyClass();
return 0;
}
MyClass* pValue;
someFunc(pValue);
This allows you to pass the argument by reference instead of by value. Hence the results are visible to the caller.
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