为什么我应该以有价值的方式返回一些东西

为什么我应该以有价值的方式返回一些东西

本文介绍了为什么我应该以有价值的方式返回一些东西,因为C ++的特性是const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Consider this function:

Thing func(){
    return something;
}

对这个函数的每次调用都是

Every call to this function, a copy of something is made and passed to the caller.

我的问题是,为什么不直接做这个( every time I想要返回值)?

My question is, why not just do this (every time I want to return something by value)?

const Thing& func(){
    return something;
}

这样,我们不会冒着复制的风险没有理由这样做。如果客户端只需要从某些东西中读取,而不是'写入',那么const引用可以做到这一点。如果客户端确实需要一个副本,它可以简单地将const引用赋值给一个变量,例如:

This way, we're not risking copying something without a reason to do so. If the client only needs to 'read' from something, but not 'write' to it, a const reference can do exactly that. And if the client does need a copy, it can simply assign the const reference to a variable, e.g.:

Thing thing = func(); // the object is passed by const reference, and then copied.

那么是否有理由简单地按价值回报?

So is there ever a reason to simply return by value?

顺便说一下,这并不是说我非常在意优化,而只是我没有看到一个理由永远不会仅仅依靠价值回报。

By the way, it's not that I care so much about optimization, it's just that I don't see a reason to ever return simply by value.

后续问题:阅读答案,我知道每种方法都有优点和缺点。是否有默认?例如。 默认为按值返回?或者它是纯粹基于特定情况?

Follow up question: reading the answers, I understand that there are pros and cons for each method. Is there a default? E.g. "default to returning by value"? Or is it purely based on the specific case?

推荐答案

因为如果你的对象(无论什么原因)是在堆栈上创建的被调用的函数,返回并使用对它的引用是未定义的行为。

Because if your object (for whatever reason) was created on the stack of the called function, returning and using a reference to it is undefined behavior.

通过值返回,编译器有时可以优化返回值,并且没有危险的悬挂引用。随着C ++ 11和移动语义的提升到一个新的水平。

With return-by-value the compiler can sometimes optimize the return and there are no dangerous dangling references. With C++11 and move semantics this is brought to a new level.

说通过引用返回总是更好,而不是按价值,每种情况下使用一个,必须单独考虑。

It doesn't quite make sense to say "it's always better to return by reference rather than by value", each case where one is used, must be considered separately.

这篇关于为什么我应该以有价值的方式返回一些东西,因为C ++的特性是const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:36