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

前端 未结 5 482
暗喜
暗喜 2020-12-09 03:37

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 fun

相关标签:
5条回答
  • 2020-12-09 04:25

    The short answer is that parameters in C++ are passed by value, so your function receives a copy of that pointer. Once you overwrite it inside your function, the change is lost.

    Your snippet however wants the change to be visible from the outside, so it needs a way to overwrite the actual pointer to the object, so it has to get a copy of a pointer to the pointer to the class, so it can overwrite the inner pointer and have it be visible from the outside.

    0 讨论(0)
  • 2020-12-09 04:27

    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.

    0 讨论(0)
  • 2020-12-09 04:27

    Using a single pointer just wouldn't work. Consider:

    int someFunc(MyClass* retObj) {
        retObj = new MyClass();
        return 0;
    }
    
    MyClass* ptr = null;
    someFunc(ptr);
    // ptr is still null and we've got a memory leak
    

    There are ways to make this work other than using a pointer to pointer, relative merits of which could be debated.

    0 讨论(0)
  • 2020-12-09 04:29

    The canonical way to return an X is to pass a pointer to X. If X is a "pointer to MyClass", the canonical way to return it is to pass a "pointer to pointer to MyClass". You can't just pass a pointer to a MyClass to the function because the caller has no idea what the value of that pointer should be.

    0 讨论(0)
  • 2020-12-09 04:34

    Those two stars (double pointer) means a "pointer-to-a-pointer". This is a way of getting around the restriction where you can't return two things from a function in C++ (in your case, a return code indicating success or failure, and the newly allocated object).

    0 讨论(0)
提交回复
热议问题