Anthony Yershov
Anthony Yershov

Reputation: 307

Will GNU GCC keep track of objects which have previously been dereferenced using the arrow operator?

Using the following struct,

struct A
{
    A(int d1, int d2)
    {
        data1 = d1;
        data2 = d2;
    }

    int data1, data2;
};

will the last line in the function below dereference the pointer again, or will the compiler know to use the previously dereferenced object?

int main()
{
    A* a = new A(1, 2);

    //dereference a
    cout << a->data1 << endl;

    //dereference a again?
    cout << a->data2 << endl;
}

If not, are there any compilers that might do this?

I know that I can perform an experiment to test my question however I do not know assembly language very well.

Upvotes: 1

Views: 67

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385375

Yes, it is possible that in cases like this the generated code will not literally perform another dereference. This will occur when the compiler can tell for sure that a won't change between the two statements.

This is a common category of optimisation, and is the cause of many bugs when people violate strict aliasing rules (because this potentially breaks the compiler's ability to detect that a hasn't changed).

Upvotes: 1

Related Questions