Sim
Sim

Reputation: 4194

passing a pointer of a reference/passing a reference of a reference

Do I get a usual pointer as I pass a pointer to a reference of a variable or do i get a pointer to the reference? And what do i get as I pass a reference to a reference? I am using the stack implementation of the standard library in a class, and i want to have some wrapper methods to prevent illegal access of the stack, but i am getting strange segfaults which i narrowed down to my getter-methods considering the stack.

Should those methods give back a clean reference/pointer to the original variable stored in the stack?

int& zwei() { return stack.top() };

and

int* eins() { return &stack.top() };

Upvotes: 2

Views: 296

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477570

There is no such thing as a "pointer to a reference". References are aliases, and so taking the address of any of them will give a pointer to the same object:

int a;
int & b = a;

assert(&a == &b);

Your functions both return a valid result provided that the stack object is still alive in the scope of the function return.

std::stack<int> s;

int & foo() { return s.top(); }  // OK, maybe
int * goo() { return &s.top(); } // ditto

int & boo() { std::stack<int> b; return b.top(); } // No! Dangling reference!

You should also check that the stack isn't empty, in which case top() is not valid.

(I should also council against calling a variable by the same name as a type, even though the type's name is std::stack.)

Upvotes: 3

Related Questions