dereferencing a pointer when passing by reference(通过引用传递时取消引用指针)
问题描述
通过引用传递给函数时取消引用指针会发生什么?
what happens when you dereference a pointer when passing by reference to a function?
这是一个简单的例子
int& returnSame( int &example ) { return example; }
int main()
{
int inum = 3;
int *pinum = & inum;
std::cout << "inum: " << returnSame(*pinum) << std::endl;
return 0;
}
是否产生了临时对象?
推荐答案
取消引用指针不会创建副本;它创建一个 lvalue 指向指针的目标.这可以绑定到 lvalue 引用参数,因此函数接收对指针指向的对象的引用,并返回对相同对象的引用.这种行为是明确定义的,不涉及临时对象.
Dereferencing the pointer doesn't create a copy; it creates an lvalue that refers to the pointer's target. This can be bound to the lvalue reference argument, and so the function receives a reference to the object that the pointer points to, and returns a reference to the same. This behaviour is well-defined, and no temporary object is involved.
如果它按值获取参数,那么这将创建一个本地副本,并返回对该副本的引用会很糟糕,如果访问它会产生未定义的行为.
If it took the argument by value, then that would create a local copy, and returning a reference to that would be bad, giving undefined behaviour if it were accessed.
这篇关于通过引用传递时取消引用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过引用传递时取消引用指针
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
