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 are to use them, so in do_something I should use get()
in order to access value
. My question is: will compiler optimize-out the getter, so it will be equivalent to accessing the data directly? Or I still will gain performance if I access it directly (what would imply worse design)?
A::do_something()
{
x = get();
// or...
x = value;
}
When the method is not virtual, compilers can optimize it. Good compilers (with link-time optimization) can optimize even if the method is not inline
and defined in separate .cpp file. Not so good ones can only do that if it's declared inside the class definition, or in the header file with inline
keyword. For virtual methods, it depends, but most likely no.
The compiler will almost certainly inline such a trivial getter, if it's got access to the definition.
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