Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ why double pointer for out/return function parameter?

Tags:

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?

like image 482
Bret Kuhns Avatar asked Dec 13 '11 19:12

Bret Kuhns


1 Answers

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.

like image 69
JaredPar Avatar answered Oct 14 '22 14:10

JaredPar