Reputation: 6950
I'm aware of the static order initialization fiasco, but I'm wondering if the following would also trigger it:
const static Point center = CalculateCenter();
static Point currentPoint = center;
I'd like to have two static variables (internal linkage in a TU), one is initialized and constant, the other one is shared across a great deal of instances but at first it should have the same value of center
.
Would this trigger static order initialization fiasco? If it does, how should I code this instead?
Upvotes: 0
Views: 56
Reputation: 458
As the previous answer said, in the same translation unit there is no problem. The order is preserved.
If the two static variables are not in the same translation unit you should use function instead as follow:
//somewhere in a class X
static const Point& center() { const static Point _center = CalculateCenter(); return _center; }
//somewhere in a class Y
static Point& currentPoint() { static Point _current_point = X::center(); return _current_point; }
Then when you need the variables you use the function accessors X::center()
or Y::currentPoint()
.
Upvotes: 2
Reputation: 48928
If they are all in the same compilation unit, then it's fine (if you order them correctly). But if they're not, then it's undefined behavior, because of the initialization order. You could however declare center
as constexpr
instead of const
, then center
is known at compile time which should be ok, but then CalculateCenter()
would also need to be a constexpr
, which is maybe not possible in your case.
Upvotes: 3
Reputation: 5073
It is clearly defined that within one compilation unit the order is well defined and it follows declaration order. The problem appears across different units which is not a case here so the code is totally fine.
Upvotes: 3