Recently i did some performance tests using getter and setter methods. I'm still not sure which is the best method to use them in c++. (there is no difference using small types like int etc.)
string i;
string GetTest()
{
return i;
}
void SetTest(string i)
{
this->i = i; //copy
}
This would be the way, how I would use it in java/C#. No reference/pointer and very slow in c++. For strings, vectors and other "big" types this is very slow and bad if it gets called frequently
string i;
const string& GetTest()
{
return i;
}
void SetTest(const string& i)
{
this->i = i; //copy
}
At the moment I'm using this version above, it's much faster than using no references for the parameter and return value and with const I make sure, it won't be changed.
string* i;
string& GetTest()
{
return *i;
}
void SetTest(string& i)
{
this->i = &i;
}
This version, using a pointer is faster than just using references, but I think it's harder to read, and if you want to work with the value inside the class, you have to work with the pointer.
Beside using references / pointers it might also improve the performance a little bit by inlining frequently called getter & setters, since they are small functions.
inline GetTest(){....}
inline SetTest(){....}
But as already mentioned, I'm still not sure which would be the best way in c++ to use them, or if there are other ways. It would be good to eliminate these ambiguities.
Edit:
Coming back to this after nearly 4 years, here is my advice I would give now for modern C++: (more helpful than any text)
https://www.youtube.com/watch?v=xnqTKD8uD64 51:00
I recommend to watch the full video, Herb Sutter such an amazing talker, in general follow CppCon.