Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should accessors return values or constant references?

Suppose I have a class Foo with a std::string member str. What should get_str return?

std::string Foo::get_str() const
{
    return str;
}

or

const std::string& Foo::get_str() const
{
    return str;
}

What is more idiomatic in C++?

like image 303
fredoverflow Avatar asked Jan 06 '11 10:01

fredoverflow


2 Answers

The short answer is: it depends :-)

From the performance point of view returning a reference is (usually) better: you save the creation of a new std::string object. (In this case, the creation is costly enough and the size of the object is high enough to justify make this choice at least worth considering - but this is not always the case. With a smaller or built-in type the performance difference may be negligible, or returning by value may even be cheaper).

From the security point of view returning a copy of the original value may be better, as constness can be cast away by malicious clients. This is especially to be taken into consideration if the method is part of a public API, i.e. you(r team) have no full control over how the returned value is (mis)used.

like image 157
Péter Török Avatar answered Oct 22 '22 15:10

Péter Török


One of the goals of having an accessor method is to try, at least to some extent, to abstract your class implementation from its interface.

Returning by value is better because there are no lifetime issues with the referenced object. Should you decide not to have a std::string member but, say, a std::stringstream or to create a std::string on the fly you don't have to change the interface.

Returning by const reference isn't the opposite of taking a parameter by const reference, taking a value by const reference doesn't tie your internal data representation to the external interface.

like image 27
CB Bailey Avatar answered Oct 22 '22 16:10

CB Bailey