Suppose that I have a class that has two methods. One of them should find an object in a container and return it by value, and the other one should return it by reference. Naturally, I want the first method to be const
(in the sense of this
being const
) and the second one not to be.
Is there a way to re-use the code between these two methods without introducing a third method that they both rely on? Below I've given a toy example of the problem, where one should imagine that the find
step is actually considerably more complicated.
In "possible implementation 1" below, there is an error due to the fact that I am calling (non-const
) get_ref
from within (const
) get_value
. In "possible implementation 2," the reference is created from a temporary copy of the value, which of course is a major problem.
In the case that a const
reference is desired, then of course there is no problem, but assume that I actually want an ordinary reference.
// Header:
#include <string>
#include <map>
using std::string;
using std::map;
class Test {
public:
map< string, string > stuff;
string & get_ref( const string key );
string get_value( const string key ) const;
};
// Possible implementation 1:
string Test::get_value( const string key ) const {
return get_ref( key );
}
string & Test::get_ref( const string key ) {
return stuff.find( key )->second;
}
// Possible implementation 2 (obviously wrong, but here for the sake of pointing that out):
string Test::get_value( const string key ) const {
return stuff.find( key )->second;
}
string & Test::get_ref( const string key ) {
return get_value( key );
}