Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.

inline variables do not call constructor

Harris__John
Beginner
652 Views

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
Honored Contributor III
652 Views

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

Jim Dempsey 

0 Kudos
Harris__John
Beginner
652 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.

0 Kudos
jimdempseyatthecove
Honored Contributor III
652 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. 

0 Kudos
Harris__John
Beginner
652 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;
}
 

0 Kudos
Harris__John
Beginner
652 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;
}
 
 

0 Kudos
Reply