Does the compiler optimize trivial getter methods into simple field accesses?

While I would assume that in VC++ this would be a no brainer, it's still worth asking.

When creating a getter method for a class that only returns the value of a protected/private member, does the compiler optimize this call so it's the equivalent of referencing that member without having to friend the class and without the overhead of a full method call?

Upvotes: 3

Views: 637

Answers (1)

GManNickG
GManNickG

Reputation: 504113

Yes. Both variants compile to the same thing:

struct test
{
    int x;

    int get() const { return x; }
};

__declspec(noinline) int use_x(const test& t)
{
    return t.x;
}

__declspec(noinline) int use_get(const test& t)
{
    return t.get();
}

int main()
{
    test t = { 111605 };

    // pick one:
    return use_x(t);
    //return use_get(t);
}

Note that it's not as simple as always replacing t.get() with t.x, for the compiler. Consider something like this:

t.get() += 5;

This shouldn't compile, because the result of the function call is an rvalue and += (for primitives) requires an lvalue. The compiler will check for things like that.

Upvotes: 8

Related Questions