Skip to content

Instantly share code, notes, and snippets.

@Loki-Astari
Last active June 27, 2023 03:47
Show Gist options
  • Select an option

  • Save Loki-Astari/45ad561d1a5c75a845566b171e27bc0e to your computer and use it in GitHub Desktop.

Select an option

Save Loki-Astari/45ad561d1a5c75a845566b171e27bc0e to your computer and use it in GitHub Desktop.
#include "AAA.h"
#include "ClassA.h"
size_t AAA:get_sSize() {
// Initialized on first use.
static size_t sSize = ClassA::Insert( "AAA" );
// return the value that is only initialized once.
return sSize;
}
#pragma once
class AAA
{
public:
static size_t get_sSize();
};
#include "ClassA.h"
#include <iostream>
// This is the function you want
// This will force your vector to be initialized before it is used.
std::vector<std::string>& ClassA::getSVec() {
// Becuase this memeber is static.
// It will be initalized of first use.
// It will be destroyed at the end of the application like
// all other global (Static storage duration) objects.
static std::vector<std::string> sVec;
// Simply return a reference to the object.
// You can now gurantee that it is created before it is used.
return sVec;
}
size_t ClassA::get_sSize()
{
static size_t sSize = ClassA::Insert( "ClassA" );
return sSize;
}
size_t ClassA::Insert( const std::string& str )
{
getSVec().push_back( str );
return getSVec().size();
}
void ClassA::Print()
{
for( const auto& str : getSVec() )
std::cout << str << std::endl;
}
#pragma once
#include <vector>
#include <string>
class ClassA
{
static std::vector<std::string>& getSVec();
public:
static size_t Insert( const std::string& str );
static void Print();
static size_t get_sSize();
};
#include "ClassB.h"
#include "ClassA.h"
size_t ClassB::get_sSize()
{
static size_t sSize = ClassA::Insert( "ClassB" );
return sSize;
}
#pragma once
class ClassB
{
public:
static size_t get_sSize();
};
//main.cpp
#include "AAA.h"
#include "ClassB.h"
#include "ClassA.h"
int main()
{
ClassA::Print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment