Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is initialization order guaranteed

Tags:

c++

c++11

I am using something like the following sections of code to do some initialization. I know that the initialization of p<T>::i_ is unordered. I believe that h is ordered, so I should be able to reason about the order that it is initialized in. Given that the header for p is included before the definition of h, is there any guarantee that p<T>::i_ will be initialized before h?

struct helper
{
   template <typename T>
   helper(const T&, int i)
   {
      p<T>::i_::push_back(i);
   }
};
static helper h;

The class p is defined below.

template <typename T>
struct p
{
   static std::vector<int> i_;
};
template <typename T>
std::vector<int> p<T>::i_;
like image 727
Graznarak Avatar asked Dec 20 '22 01:12

Graznarak


1 Answers

The order of initialization of objects with static storage duration is undefined across translation units, and sequential within each translation unit.

In your particular case things are more complicated, since one of the objects with static storage is a static member of a template class. What that means in a practical way is that each translation unit that accesses the member p<T>::i_ will create the symbol, and add the appropriate initialization code. Later the linker will pick one of the instances and keep it. Even if it looks like p<T>::i_ is defined before h in your translation unit, you don't know which instance of p<T>::i_ will be kept by the linker, and that might be one in a different translation unit and thus the order is not guaranteed.

In general it is a bad idea to have global objects, I would suggest that you try to redesign your program without those globals.

like image 96
David Rodríguez - dribeas Avatar answered Jan 04 '23 21:01

David Rodríguez - dribeas