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

前端 未结 5 491
暗喜
暗喜 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: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.

提交回复
热议问题