initialization order of static const initialized with functions

时间:2016-08-31 17:03:05

标签: c++ class oop c++11 static

-->

In short, I need to initialize a const static member with some value obtained from a file and keep it thereby same for every object derived from it.

So let's say I've a program -

#include <fstream>
#include <iostream>
#include <string>

class A
{
public:
static const int VAL1;
static const int VAL2;
};

int F(const std::string);

const int A::VAL1 = F("1.txt");
const int A::VAL2 = F("2.txt");

int F(const std::string filename)
{
  std::ifstream file(filename);
  int result = 0;
  file >> result;
  return result;
}

int main () {
  std::cout << A::VAL1 << " " << A::VAL2 << "\n";
}

Is it guaranteed that static members will be always initialized before creation of objects, because that's what I want :/

1 个答案:

答案 0 :(得分:1)

static data member exists even when no instances of the class exist, that guarantee the presence of an initialized static member when an instance with automatic storage is created.

An exception of this is when there's an instance of the class with static storage that is declared before the initialization of the static member in the same translation unit, the static variables are initialized in the same order they appear.

相关问题
最新问题