猿问

返回C ++引用变量的做法是邪恶的吗?

返回C ++引用变量的做法是邪恶的吗?

我觉得这有点主观; 我不确定这个意见是否会一致(我已经看过很多代码片段,其中返回了引用)。

根据对这个问题的评论我刚刚问过,关于初始化引用,返回引用可能是邪恶的,因为,[据我所知]它更容易错过删除它,这可能导致内存泄漏。

这让我很担心,因为我跟随了一些例子(除非我想象事情)并且在相当多的地方做过这样的事情......我误解了吗?这是邪恶的吗?如果是这样,那有多邪恶?

我觉得因为我的指针和引用混合在一起,再加上我是C ++的新手,以及对什么时候使用的完全混淆,我的应用程序必须是内存泄漏地狱......

另外,我知道使用智能/共享指针通常被认为是避免内存泄漏的最佳方法。


守着星空守着你
浏览 333回答 3
3回答

慕姐4208626

通常,返回引用是完全正常的并且始终发生。如果你的意思是:int&&nbsp;getInt()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;i; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;i;&nbsp;&nbsp;//&nbsp;DON'T&nbsp;DO&nbsp;THIS.}这就是种种邪恶。分配的堆栈i将消失,你指的是什么。这也是邪恶的:int&&nbsp;getInt()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;int*&nbsp;i&nbsp;=&nbsp;new&nbsp;int; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;*i;&nbsp;&nbsp;//&nbsp;DON'T&nbsp;DO&nbsp;THIS.}因为现在客户端最终必须做到这一点:int& myInt = getInt(); // note the &, we cannot lose this reference!delete &myInt;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// must delete...totally weird and&nbsp; evilint oops = getInt();&nbsp;delete &oops; // undefined behavior, we're wrongly deleting a copy, not the original请注意,右值引用仍然只是引用,因此所有恶意应用程序保持不变。如果要分配超出函数范围的内容,请使用智能指针(或通常是容器):std::unique_ptr<int>&nbsp;getInt()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;std::make_unique<int>(0);}现在客户端存储一个智能指针:std::unique_ptr<int>&nbsp;x&nbsp;=&nbsp;getInt();参考也可以访问您知道生命周期在更高级别保持打开的内容,例如:struct&nbsp;immutableint&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;immutableint(int&nbsp;i)&nbsp;:&nbsp;i_(i)&nbsp;{} &nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;int&&nbsp;get()&nbsp;const&nbsp;{&nbsp;return&nbsp;i_;&nbsp;}private: &nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;i_;};在这里我们知道可以返回一个引用,i_因为无论调用我们管理类实例的生命周期,所以i_至少会存活那么久。当然,只是:没有错:int&nbsp;getInt()&nbsp;{ &nbsp;&nbsp;&nbsp;return&nbsp;0;}如果生命周期应该留给调用者,而你只是计算值。简介:如果对象的生命周期不会在调用后结束,则可以返回引用。

拉莫斯之舞

不,不,一千次没有。什么是邪恶的是引用动态分配的对象并丢失原始指针。当您new成为对象时,您有义务获得保证delete。但是看看,例如operator<<:必须返回引用,或者cout&nbsp;<<&nbsp;"foo"&nbsp;<<&nbsp;"bar"&nbsp;<<&nbsp;"bletch"&nbsp;<<&nbsp;endl&nbsp;;不行。
随时随地看视频慕课网APP
我要回答