开发者

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

Do I get a us开发者_StackOverflowual 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() };


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜