Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Harris__John
Beginner
55 Views

inline variables do not call constructor

There appears to be a bug with inline variable initialization.  The following code prints "0".  With gcc, it prints "1".

(ICC) 19.0.0.117 20180804

#include <iostream>

int flag = 0;

class C
{
public:
  C() { ::flag = 1; }
};

class D
{
public:
  static inline C c = C();
};


int main(int, char **)
{
  D d;
  std::cout << ::flag << std::endl;
}
 
 

0 Kudos
5 Replies
jimdempseyatthecove
Black Belt
55 Views

This may be a case of vendor dependent behavior between the order of a static constructor and global variable initialization.

Jim Dempsey 

Harris__John
Beginner
55 Views

Thanks, but the behavior is the same if you assert() or throw() in the constructor.  The constructor does not get called at all...ever.

jimdempseyatthecove
Black Belt
55 Views

Those may be determined at compile time.

Copy the last statement of main, and insert into first statement of the ctor and see what happens. 

Harris__John
Beginner
55 Views

Strange. If you put the iostream operation in there, it gets run, but if you put throw(0) in the constructor, it doesn't get run...using icpc.

class C
{
public:
  C() { throw(0); }
};

class D
{
public:
  static inline C c = C();
};


int main(int, char **)
{
  D d;
}
 

Harris__John
Beginner
55 Views

More to the point, this core dumps with a floating point exception, because the unordered_map ctor doesn't get run.  This is how I found the problem:

#include <unordered_map>


class C
{
public:
  C() { m.find(0); }
  static inline std::unordered_map<int,int> m;
};

int main(int, char **)
{
  C c;
  return 0;
}