M
Mikewhy
Apologies. I know this has to have been discussed, but I'm unable to google
my way past the shallower, newbie discussions of temporary's lifetime, etc.
A class Lookup contains a collection of strings referenced by some key, the
values representing, perhaps, a database lookup.. The key is representative
of its field name. Here, we're interested only in the accessor methods,
get_val() and get_value(). The first returns a copy of the string by value.
The other returns a const reference to the value.
class Lookup
{
public:
enum FieldId {
...
};
std::string get_val(FieldId) const;
const std::string & get_value(FieldId) const;
...
};
The values already exist as std::string in the Lookup object. Returning by
const reference then is direct and has the advantage of efficiency.
Returning by value, even with return value optimization, incurs at minimum a
string copy.
The question is, assuming that multithread issues are not present, how
easily can naive code cause trouble for itself with a const reference return
interface? What usage patterns (that have a chance of surviving the low
threshold of a peer review) might prove problematic?
my way past the shallower, newbie discussions of temporary's lifetime, etc.
A class Lookup contains a collection of strings referenced by some key, the
values representing, perhaps, a database lookup.. The key is representative
of its field name. Here, we're interested only in the accessor methods,
get_val() and get_value(). The first returns a copy of the string by value.
The other returns a const reference to the value.
class Lookup
{
public:
enum FieldId {
...
};
std::string get_val(FieldId) const;
const std::string & get_value(FieldId) const;
...
};
The values already exist as std::string in the Lookup object. Returning by
const reference then is direct and has the advantage of efficiency.
Returning by value, even with return value optimization, incurs at minimum a
string copy.
The question is, assuming that multithread issues are not present, how
easily can naive code cause trouble for itself with a const reference return
interface? What usage patterns (that have a chance of surviving the low
threshold of a peer review) might prove problematic?