mardi 21 mai 2019

Constant initialization of dependent non-local constant float variables w/ static storage duration in different translation units

I'm wondering whether I can rely on constant initialization when there is a dependency between two constant non-local float variables with static storage duration in two different translation units - where one is dependent on (initialized to [the value of]) the other, and where for the latter, constant initialization is performed. I'm looking for answers providing and interpreting the relevant part of the standard, particularly the C++11 standard.

// Note: the non-use of constexpr is intended (C++03 compatibility)

// foo.h
struct Foo {
  static const float kValue;
};

// foo.cpp
const float Foo::kValue = 1.5F;

// bar.h
struct Bar {
  static const float kValue;
};

// bar.cpp
#include "foo.h"
const float Bar::kValue = Foo::kValue;  // Constant initialization?

// main.cpp
#include "bar.h"
#include <iostream>

int main() { std::cout << Bar::kValue; }

  • Is the non-local (constant) variable Bar::kValue, which have static storage duration, initialized by means of constant initialization? (Which in turn answers whether it is initialized by means of static or dynamic initialization)

Details / investigations of my own

[basic.start.init]/1 states [emphasis mine]:

Constant initializationis performed:

  • if each full-expression (including implicit conversions) that appears in the initializer of a reference with static or thread storage duration is a constant expression (5.19) and the reference is bound to an lvalue designating an object with static storage duration or to a temporary (see 12.2);

  • if an object with static or thread storage duration is initialized by a constructor call, and if the initialization full-expression is a constant initializer for the object;

  • if an object with static or thread storage duration is not initialized by a constructor call and if either the object is value-initialized or every full-expression that appears in its initializer is a constant expression.

In interpret from the final bullet that Bar::kValue is initialized by means of constant initialization if Foo::kValue is a constant expression. I suspect the answer is "yes, Foo::kValue is a constant expression", and that I will find the answer in [expr.const], but here I'm stuck.

Aucun commentaire:

Enregistrer un commentaire