1

I'm expecting the following code to output 'AAA ClassA ClassB', but it's only outputing 'ClassA ClassB'. Is my expectation correct? If not, how can I make sure it's initializing all the static variables.

//main.cpp
#include "AAA.h"
#include "ClassB.h"
#include "ClassA.h"

int main()
{
    ClassA::Print();
}
// AAA.h
#pragma once
class AAA
{
public:
    static size_t sSize;
};
// AAA.cpp
#include "AAA.h"
#include "ClassA.h"

size_t AAA::sSize = ClassA::Insert( "AAA" );
// ClassA.h
#pragma once
#include <vector>
#include <string>

class ClassA
{
public:
    static size_t Insert( const std::string& str );
    static void Print();
    static std::vector<std::string> sVec;
    static size_t sSize;
};
// ClassA.cpp
#include "ClassA.h"
#include <iostream>

std::vector<std::string> ClassA::sVec;

size_t ClassA::sSize = ClassA::Insert( "ClassA" );
size_t ClassA::Insert( const std::string& str )
{
    sVec.push_back( str );
    return sVec.size();
}

void ClassA::Print()
{
    for( const auto& str : sVec )
        std::cout << str << std::endl;
}
// ClassB.h
#pragma once
class ClassB
{
public:
    static size_t sSize;
};
// ClassB.cpp
#include "ClassB.h"
#include "ClassA.h"

size_t ClassB::sSize = ClassA::Insert( "ClassB" );

When I debugged in VS, sVec did contain "AAA", but then it gets initialized again to be an empty vector. Then "ClassA" and "ClassB" gets inserted.

Tony J
  • 599
  • 5
  • 16
  • 6
    https://en.cppreference.com/w/cpp/language/siof – NathanOliver Jun 26 '23 at 22:20
  • 1
    The _question_ is not a duplicate of the one marked as a duplicate, but the answer answers your question (as does Nathan's link) – Ted Lyngmo Jun 26 '23 at 22:24
  • 1
    There is a simple solution to force the order of initialization. Put the static members inside functions. Then they will initialized on first use and destroyed in reverse order of creation. If you require a specific order you can then enforce it easily. – Martin York Jun 27 '23 at 01:33
  • https://stackoverflow.com/a/335746/14065 – Martin York Jun 27 '23 at 01:34
  • See: https://gist.github.com/Loki-Astari/45ad561d1a5c75a845566b171e27bc0e See the file classA.cpp function: `std::vector& ClassA::getSVec()` Personally I would apply the same pattern to `classA::sSize` and `classB::sSize`. – Martin York Jun 27 '23 at 03:12

0 Answers0