传递引用的指针/传递引用的引用
当我传递指向变量引用的指针时,我是否得到一个普通的指针,或者我得到一个指向该引用的指针?当我传递一个引用到一个引用时我会得到什么? 我在类中使用 标准库 的堆栈实现,并且我想要一些包装方法来防止堆栈的非法访问,但我遇到了奇怪的段错误,考虑到堆栈,我将其范围缩小到了我的 getter 方法。
这些方法是否应该返回一个指向存储在堆栈中的原始变量的干净引用/指针?
int& zwei() { return stack.top() };
和
int* eins() { return &stack.top() };
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() };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不存在“指向引用的指针”这样的东西。引用是别名,因此获取其中任何一个的地址都会给出指向同一对象的指针:
只要
stack
对象在函数范围内仍然存在,您的函数都会返回有效结果返回。您还应该检查堆栈是否为空,在这种情况下
top()
无效。(我还应该反对调用与类型同名的变量,即使类型的名称是
std::stack
。)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:
Your functions both return a valid result provided that the
stack
object is still alive in the scope of the function return.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
.)