Does the recipient have a zero cost?

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)?

A::do_something()
{
    x = get();
    // or...
    x = value;
}
+5
source share
5 answers

, . ( ) , inline .cpp. , inline. , , , .

+7

getter, .

+3

( , , inline), , .

inline, , -.

+2

, get , , ( , ). , , , , get, , , .

+1

, , :

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.

+1
source

All Articles