I've go a very simple question, but unfortunately I can't figure the answer myself.
Suppose I've got some data structure that holds settings and acts like a settings map.
I have a GetValue(const std::string& name)
method, that returns the corresponding value.
Now I'm trying to figure out - what kind of return-value approach would be better. The obvious one means making my method act like
std::string GetValue(const std::string& name) const
and return a copy of the object and rely on RVO in performance meanings.
The other one would mean making two methods
std::string& GetValue(...)
const std::string& GetValue(...) const
which generally means duplicating code or using some evil constant casts to use one of these routines twice.
#
QWhat would be your choice in this kind of situation and why?
Actually I would probably use:
std::string GetValue(const std::string& name) const;
// or
const std::string* GetValue(const std::string& name) const;
void SetValue(std::string name, std::string value);
Setter first:
SetValue
allows the compiler some optimizations that cannot be made with pass by const-reference, it's been explained in a article by Dave Abrahams, "Want Speed? Pass by Value."
Setter
is usually better, because you can check the value being set whereas with a plain reference you have no guarantee that the caller won't do anything stupid with the data.For the getter:
std::wstring
because you need some settings in UTF-8...That depends on the usage. Should GetValue("foo") = "bar"
make sense? In that case, return by value does not do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With