From: restor on
> Can anyone think of any other reasons to prefer returning a string by
> value. I am encountering some opposition to this, mainly in the name
> of performance. The performance has not been measured (of course) but
> this is often the case with 'performance' arguments. Unfortunately,
> "show me the figures" cuts no ice.

Apart from performance (by-value can be faster as pointed out in
http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/) the
simplest argument for by-value is elegance and clarity.

string process( string name, string content );

simply reads smoother than

string const& process( string const& name, const string &
content );

There is a general best-practice statement in programming that one
should avoid premature optimization. You may consider your case a good
example of this practice. First pass by value (it is clearer, safer
(dangling refs, multithreading), shorter) and if you find that
performance is insufficient, and if you measure that substituting by-
ref increases performance significantly (and it may not), only then
should you change to by-ref.

Regards,
&rzej

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Eyal Ben David on
On Dec 2, 3:06 pm, Andrew <marlow.and...(a)googlemail.com> wrote:
[...]
>
> Can anyone think of any other reasons to prefer returning a string by
> value. I am encountering some opposition to this, mainly in the name
> of performance. The performance has not been measured (of course) but
> this is often the case with 'performance' arguments. Unfortunately,
> "show me the figures" cuts no ice.
>

Look at the following code:

#include <string>

// Forward decl
//
void print_name(const std::string& name);
//------------------------

class Person {
public:
Person(const std::string& name);
const std::string& name_ref() const;
std::string name_val() const;
};
//------------------------

void print_person_ref(const Person& p) {
print_name( p.name_ref() );
}
//------------------------

void print_person_val(const Person& p) {
print_name( p.name_val() );
}
//------------------------


In the assembly listing after the compilation with all optimizations
(gcc 4.4.1), the value function "print_person_val()" is much larger
and has many more instructions than the reference function
"print_person_ref()". This is alone is not a proof that the return-by-
const-ref is faster but this is likely the case. Besides, code size is
a metric too.





--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]