1

What will be good programming practice out of two below funcs:

  1. This:

    std::string buildvalue(const std::string &in) {
        std::string out;
        out = // Do some calulation bases on input
        return out;
    }
    
  2. Or this:

    void buildvalue(const std::string &in, std::string &out) {
        out = // Do some calulation bases on input
    }
    

Cautious with 2 function is that the caller may pass non-empty string. Is there any points to note.

PURVESH PATEL
  • 199
  • 2
  • 8
  • 1 (this must be at least 16 chars long :) ) – hellow Jul 11 '18 at 14:06
  • Both have some advantages and disadvantages which are worth considering in specific contexts – bartop Jul 11 '18 at 14:07
  • 10
    Return-value optimizations (especially copy-elision) and move semantics plays a big part making 1 a very good solution. – Some programmer dude Jul 11 '18 at 14:07
  • 2
    A user passing a non-empty string to `out` is no different from a user assigning the result of the first solution to a non-empty string. I don't see why one has to be extra cautious about it. – François Andrieux Jul 11 '18 at 14:11
  • 1
    Unless you have to return multiple values, and even then you can get away without out parameters, you should return the output of the function. – NathanOliver Jul 11 '18 at 14:11
  • See Howard's answer here: https://stackoverflow.com/questions/4986673/c11-rvalues-and-move-semantics-confusion-return-statement/4986802#4986802 Basically, in modern C++ #1 is considered _in general_ to be the best practice – Chad Jul 11 '18 at 14:19
  • I would go with 1). I would only use output parameters if you need to return more than one item. But this question boils down to your personal preference in most cases. – nonremovable Jul 11 '18 at 14:58

1 Answers1

0

In first case, compiler will be able to optimize return value. It will place return value in calling function. For example,

std::string foo(...) { ... }

// ...

std::string result = foo(...);

Compiler will place foo return value right on the result spot. It relieves us from reference argument and premature variable declaring. Slightly C++17: Instead const std::string& you can use std::string_view. Its advantage is optional for creating temp std::string in following case:

void foo(const std::string&);
// ...
foo("hello world"); // here will be create std::string object

With std::string_view (c++17)

void foo(std::string_view);
// ...
foo("hello world"); // more productive

+ std::string have operator std::string_view, that leads its to std::string_view

acade
  • 245
  • 2
  • 7