Reputation: 155
I try to get the address of a pointer that is returned by a class member function:
class Test{
...
char* d;
...
char* getData(){
return d;
}
...
}
Now I try to get the address of d (assume that *d has a valid value):
Test t;
char** pd = &t.getData();
This gives a syntax error and won't compile on VC2010. How can I get the address of the member pointer variable?
Upvotes: 1
Views: 254
Reputation: 69977
Your getData()
function returns a copy of the pointer. If you want to take the address of the original pointer member, you'd have to change it so that it returns a reference to the pointer:
char *&getData() { return d; }
(Whether returning references to internal pointers and taking their address is a good idea from a design point of view is a different matter.)
Upvotes: 0
Reputation: 1092
Short version: You're trying to take the address of an rvalue, which is illegal.
Slightly longer version: When you do t.getData()
, the *d
is returned by value. This is easy to forget because most of the time, when you're working with pointers, you don't worry about pass-by-value versus pass-by-reference. You just return the pointer since it's small.
Here,
char** pd = &t.getData();
the return value of t.getData is a copy of the pointer, and it's an rvalue, meaning it's temporary and will cease to exist after the expression ends. You can't take the address of an rvalue for that reason -- it'd be invalid as soon as the statement ends. If you put that address in an lvalue however, it works just fine:
Test t;
char* temp = t.getData();
char** pd = &temp;
That's because now temp is an lvalue, and you can take its address.
For what you're trying to do though, you might be better off having getValue()
return a char**
.
Upvotes: 2