Function in C++ returns by value or by reference?

后端 未结 7 960
醉梦人生
醉梦人生 2020-12-02 14:36

When a function (callee) returns a quantity to the caller function, is it returned by value or by reference?

The thing is I have written a function which builds a ve

7条回答
  •  半阙折子戏
    2020-12-02 15:37

    C++ functions can return by value, by reference (but don't return a local variable by reference), or by pointer (again, don't return a local by pointer).

    When returning by value, the compiler can often do optimizations that make it equally as fast as returning by reference, without the problem of dangling references. These optimizations are commonly called "Return Value Optimization (RVO)" and/or "Named Return Value Optimization (NRVO)".

    Another way to for the caller to provide an empty vector (by reference), and have the function fill it in. Then it doesn't need to return anything.

    You definitely should read this blog posting: Want Speed? Pass by value.

提交回复
热议问题