Intel® C++ Compiler
Support and discussions for creating C++ code that runs on platforms based on Intel® processors.
7646 Discussions

inline variables do not call constructor

Harris__John
Beginner
228 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
Black Belt
228 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
228 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
228 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
228 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
228 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;
}
 
 

Reply