当通过引用传递时取消引用指针 [英] dereferencing a pointer when passing by reference

查看:115
本文介绍了当通过引用传递时取消引用指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过引用一个函数来解引用指针时会发生什么?



这是一个简单的例子

  int& returnSame(int& example){return example; } 

int main()
{
int inum = 3;
int * pinum =&英语

std :: cout<< inum:< returnSame(* pinum)<< std :: endl;

return 0;

}

是否生成了临时对象?

解决方案

解除引用指针不会创建副本;它创建指向指针的目标的 lvalue 。这可以绑定到 lvalue 引用参数,因此函数接收对指针指向的对象的引用,并返回对该引用的引用。此行为是定义明确的,不涉及临时对象。



如果它接受的值是参数,那么会创建一个本地副本,并返回一个引用将是坏的,给定未定义的行为,如果它被访问。 / p>

what happens when you dereference a pointer when passing by reference to a function?

Here is a simple example

int& returnSame( int &example ) { return example; }

int main()
{
  int inum = 3;
  int *pinum = & inum;

  std::cout << "inum: " <<  returnSame(*pinum) << std::endl;

  return 0;          

}

Is there a temporary object produced?

解决方案

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.

这篇关于当通过引用传递时取消引用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆