When to use Pointer-to-Pointer in C++?

后端 未结 6 1631
小鲜肉
小鲜肉 2021-02-13 20:38

I was wondering when we use Pointer to Pointer in C++ and why we need to point to a pointer? I know that when we point to a pointer it means we are saving the memory address of

6条回答
  •  迷失自我
    2021-02-13 20:56

    Anytime you're dealing with C libraries. There are two common answers for the same question in C :

    First, anytime you want doubly subscripted array, like :

    int main(int argc, char** argv) 
    

    Second, anytime you want another return value from a function. There are many functions in libgit2 that do this because they wish to return a meaningful error type as opposed to just null, like the first argument in git_branch_create for example.

    You could return a two item struct of course, but that's usually two extra lines of code. In fact, the pointer-to-pointer lets you write the pointer directly into a struct where it'll live.

    In C++, you'd avoid using pointers directly whenever suitable C++ data types exist, and my libgit2 example is subsumed by C++'s exceptions, but..

    You cannot call C++ from most high level languages, so if you're writing a library that you want available in say Perl, Python, and C++, then you write it in C.

提交回复
热议问题