C++ references vs return values

前端 未结 4 1874
天涯浪人
天涯浪人 2021-01-12 15:34

I understand the principle point of references is to avoid making copies of large structures, but what if a function you\'re writing itself creates a large structure? Is it

4条回答
  •  隐瞒了意图╮
    2021-01-12 15:57

    The first example should presumably be more like one of these two:

    void getLines(std::string in, std::vector &out);
    void getLines(std::string in, std::vector *out);
    

    The second style is often more convenient, and can in theory be made mostly as efficient as the first one:

    http://en.wikipedia.org/wiki/Return_value_optimization

    Whether this is seen in practice depends on the compiler, optimization levels, and whether the compiler can spot the opportunity in the first place.

    Whilst I don't speak for everybody, I've never actually managed to get compilers to take advantage of RVO, even with simple objects that don't do anything fancy. So I therefore personally recommend the first approach, because you are guaranteed to get the desired behaviour, on every compiler, and (which seems relevant for me...) for every programmer's code -- i.e., that the object created to hold the return value is filled in directly by the called function, without any extra copies.

    (The cost of default-constructing the result object, which is something that could potentially be avoided were RVO to be taken advantage of, is usually not significant compared to the copy the compiler might be unable to avoid.)

    Another point to note would be that if attempting to avoid unnecessary copies, passing objects by const reference instead of by value is often a good idea, e.g.:

    void getLines(const std::string &in, std::vector &out);
    void getLines(const std::string &in, std::vector *out);
    

提交回复
热议问题