0
  1. pass * as a function parameter
#include <iostream>

class A {

 public: 
  A() {}

};


class B : public A{
 public:
  B() {}

};

void foo(A* a) {
 a = new B();

}

void ff() {
  A a;
  foo(&a);
}
  1. pass ** as a function parameter
#include <iostream>

class A {

 public: 
  A() {}

};


class B : public A{
 public:
  B() {}

};

void foo(A** a) {
 *a = new B();

}

void ff() {
  A* a;
  foo(&a);
}

When I see leveldb, I am in a puzzle about this.

The specific code is the following.

https://github.com/google/leveldb/blob/master/db/db_impl.cc#L1537

I think it's ok to use FileLock lock

Then pass &lock to LockFile(const std::string& filename, FileLock* lock)

LockFile function is this

user438383
  • 5,716
  • 8
  • 28
  • 43
stackover
  • 15
  • 4
  • What exactly is your question? – DYZ Jul 27 '21 at 05:51
  • Does this answer your question? [Why use double indirection? or Why use pointers to pointers?](https://stackoverflow.com/questions/5580761/why-use-double-indirection-or-why-use-pointers-to-pointers) – prehistoricpenguin Jul 27 '21 at 05:55

1 Answers1

1

Passing double pointer and just a pointer are not the same

void foo(A* a) {
 a = new B();

}
  1. Change an input pointer to another value. The result will not reflect in the callee ff(). It's merely change the argument.
void foo(A** a) {
 *a = new B();

}
  1. Change a pointer to another pointer and change the value, which is "the another pointer", of this pointer points to . The result will reflect in ff()

According to the ff(), I assume you have a follow up question which need to operate a after foo() is called. So second one might be a proper way.

For FileLock, I believe you're referring to this implementation.

It's using double pointer because it wants to replace the entire content of FileLock.

Live demo

Followup: Why it chose using double pointer instead of pass by reference?

Because reference is not possible to be replaced, my assumption is that it chose it chose to replace the whole content which is simpler than make the implemention complex for re-initialization.

Louis Go
  • 2,213
  • 2
  • 16
  • 29
  • just use `FileLock lock` and pass `&lock` to `LockFile(const std::string& filename, FileLock* lock)` also can replace the entire content of `FileLock` – stackover Jul 27 '21 at 06:07
  • @stackover Have you tried that? You can only change the value of the argument pointer. Replacing the argument doesn't reflect to callee. – Louis Go Jul 27 '21 at 06:09
  • I don't understand why I was so confused about this in the first place. uhhhh – stackover Jul 27 '21 at 06:31
  • @stackover I face palm all the time when I found the solution. It's good to take a walk when you can't figure out something :) – Louis Go Jul 27 '21 at 12:25