Reputation: 2348
I am looking over some open source code and they listed some strange instance in a class defined as:
Obj *&obj;
I had no idea that was possible! What does that mean or even do? The pointer and reference symbols should counteract in my opinion. But maybe it does something special I do not know about?
Looking in the code, they use it as if the instance was a pointer. ie: obj->method()
. So then why did they include the &
?
Upvotes: 1
Views: 70
Reputation: 104698
That's a reference to a pointer. After all, a pointer is also a value. You might use it to reassign a pointer held by the caller. To illustrate:
bool allocate(t_object*& p) {
assert(0 == p);
p = new t_object;
...
}
Then:
t_object* obj(0);
if (!allocate(obj)) {...}
// obj now points to something
Some people find it easier to manage/read that its most direct alternative (bool allocate(t_object** p)
).
As to why a reference to a pointer was chosen in the program -- there's not enough context, but you can ask yourself if the program would be better if the member were declared t_object** const
?
Upvotes: 1
Reputation: 361462
That is reference to a pointer. Think in this way:
A *pa = new A(); //pa is pointer to A
A * & rpa = pa; //rpa is reference to pa
rpa = nullptr; //it modifies pa as well
if ( pa == nullptr )
{
std::cout << "pa is nullptr" << std::endl;
}
It will print "pa is nullptr" on the console.
If you find A * &
difficult to read, then you can use typedef as:
typedef A* PA;
PA & rpa = pa; //same as before
Upvotes: 2
Reputation: 4507
The code like you wrote it won't compile, since it declares a reference to a pointer, but the reference is uninitialized. For example, the following code won't compile:
string *&s;
(unless it's a member in a class), but this will:
string *p;
string *&s = p;
Another possibility, is that this is just a typo and they meant to write Obj *obj;
;)
Upvotes: 2
Reputation: 258608
It's a reference to a pointer. A pointer is a data-type, why shouldn't you be allowed to have references to one?
It means the same thing as any other type reference - it's an alias for a pointer.
Upvotes: 0