Alakanu
Alakanu

Reputation: 325

Do modern C++ compilers optimize away repeated accesses to the same data member of a class?

Consider:

class A
{
public:
    const int& my_int_member() const { return my_int_member; }
    const double& my_double_member const {return my_double_member; }
private:
    int my_int_member;
    double my_double_member;
};

class B
{
public:
    const A& my_A_member() const { return my_A_member; }
private:
    A my_A_member;
};

Do modern c++ compilers (e.g. msvc, clang, gcc), set with the maximum optimization level each one provides, usually recognize and optimize away repeated accesses to the same data member as in:

B b;
do_stuff(b.my_A_member().my_double_member(), b.my_A_member().my_int_member());
double c = b.my_A_member().my_double_member() + b.my_A_member().my_int_member();

That is, do they realize that they can reuse the same reference or do they just do the access again?

Upvotes: 2

Views: 111

Answers (1)

Jarod42
Jarod42

Reputation: 217085

If definition is visible, and if compiler can prove that it does the same things (optimization with the as-if rule) (which is more tricky that we can thing, with aliases, global accesses, ...), it can do it (and probably does it).

But imagine that we modify a little your example to (b is no longer local, but given as parameter):

void foo(B& b)
{
    do_stuff(b.my_A_member().my_double_member(), b.my_A_member().my_int_member());
    double c = b.my_A_member().my_double_member() + b.my_A_member().my_int_member();
}

Can do_stuff modify a global B which would be the parameter of foo. Without definition, the answer is yes. So compiler has to reload b.my_A_member() after the call to do_stuff

For readability, I would anyway do:

B b;
const auto& a = b.my_A_member();
do_stuff(a.my_double_member(), a.my_int_member());
double c = a.my_double_member() + a.my_int_member();

Upvotes: 3

Related Questions