What will be good programming practice out of two below funcs:
This:
std::string buildvalue(const std::string &in) { std::string out; out = // Do some calulation bases on input return out; }
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.