Search code examples
c++pointersinitialization

In what order are objects initialized when mixing pointers and non-pointer objects?


Take the following code:

Foo *foo = fooFactory();
Bar bar(foo);

I have three questions:

  1. Is this safe? In other words, am I guaranteed that fooFactory() will be called and foo initialized before Bar's constructor is run (assuming fooFactory() doesn't throw)?
  2. Does the answer to question #1 change if this is part of a function, part of a class, or just a bare declaration outside any blocks?
  3. Does the answer change if Bar's constructor doesn't actually take a Foo pointer, but references the foo variable directly?

Thank you for your time.


Solution

  • In C++ (and C), statements execute (or appear to execute) in the order they appear in the source code. Under the as-if rule, out-of-order execution may occur when statement B has no dependencies on statement A in order to improve performance. Thus, given:

    int i = 1;
    int j = 2;
    int k = i + j;
    

    The first two statements might be executed out of order, but the third must not be. (Of course, in real life, simple statements like this are often optimised out, but you get the idea).

    So, in the code you posted, the second statement uses the result of the first, so the statements will be executed in order.