当函数返回值是一个指针并且返回类型是c ++中的引用时会发生什么? [英] what happens when the function returning value is a pointer and the returning type is a reference in c++?

查看:477
本文介绍了当函数返回值是一个指针并且返回类型是c ++中的引用时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

男生,我刚从老师那里得到了一个奖金问题!感谢您帮助我!



下面的sub2不会导致运行时错误,但可能有一些其他
问题。问题是什么?



在此输入代码

  sub2(int& a,int& b){
int * pc = new int;
* pc = a - b;
returns(* pc);
}


解决方案

泄漏。




  • 如果此函数的用户仅依赖函数的签名,他将假设函数返回一个引用到某个人拥有的对象。因此,分配的对象将不会被释放。

  • 当然,如果用户知道这个技巧,他仍然可以通过参考

    >
  • 如果函数用于较大的表达式(这是相当诱人的,给定签名),如 sub(3,sub(2,1)) 他不会有机会捕获临时引用。




请注意,此函数MIGHT还会抛出 bad_alloc if有内存分配的问题。


guys, I just got a bonus question from my teacher! Thanks for helping me !!

The sub2 below does not result in a run-time error, but there may be some other problem. What is the problem?

enter code here

int& sub2 ( int& a , int& b ){
int * pc = new int ;
*pc = a - b ;
return (*pc ) ;
}

解决方案

This function MIGHT lead to memory leaks.

  • If the user of this function just relies on the signature of the function, he'll assume that the function returns a reference to an object that someone else owns. Hence the object that was allocated will not be released.

  • Of course, if the user is aware of the trick, he could still delete the object by taking the address of the reference

  • If the function is used in a larger expression (which is quite tempting, given the signature), such as sub(3, sub(2,1)) he will not get the opportunity to catch the temporary reference.

Note that this function MIGHT also throw a bad_alloc if there's an issue with the memory allocation.

这篇关于当函数返回值是一个指针并且返回类型是c ++中的引用时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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