I have a simple class:
class A { public: int get() const; private: void do_something(); int value; } int A::get() const { return value; }
The getter function is simple and straightforward. Getters should use them, so in do_something I have to use get()to access value. My question is: will the compiler optimize getter, so it will be equivalent to accessing data directly? Or am I still getting performance if I access it directly (which would mean worse design)?
get()
value
A::do_something() { x = get(); // or... x = value; }
, . ( ) , inline .cpp. , inline. , , , .
inline
getter, .
( , , inline), , .
inline, , -.
, get , , ( , ). , , , , get, , , .
, , :
int& get();
Now it returns the link and can be changed. But imho is not entirely clean, you should also define a setter and use it to write the changed value:
int get() const; void set(int); ... A::do_something() { x = get(); set(value); }
Setter performance depends on your compiler. Most modern compilers can embed simple getters / setters, so there should be no performance loss.