Why should I ever return something by value, since C++ features const references?

前端 未结 3 1281
忘掉有多难
忘掉有多难 2021-02-12 15:34

Consider this function:

Thing func(){
    return something;
}

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

3条回答
  •  你的背包
    2021-02-12 16:07

    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.

    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.

提交回复
热议问题