mercredi 12 avril 2023

How do I create a static member variable of an object that has static variables itself? [duplicate]

Is there a robust way to write a class that has a static member variable when that object itself has static variables of its own? In this example provided below, where Bar has a static variable of type Foo, and Foo has a static variable of type string, I am getting a seg fault when bar.cpp is compiled before foo.cpp. How could I structure this so that it works no matter the order in which the files are provided?

foo.h

#ifndef FOO
#define FOO
#include <string>

class Foo {
public:
  static const std::string STATIC_FOO
  Foo(): m_foo(STATIC_FOO) {};
  std::string m_foo;
};

#endif

foo.cpp

#include <string>
#include "foo.h"
const std::string Foo::STATIC_FOO = "foo";

bar.h

#ifndef BAR
#define BAR
#include "foo.h"

class Bar {
public:
  static Foo s_foo;
};

#endif

bar.cpp

#include "foo.h"
#include "bar.h"
Foo Bar::s_foo;

main.cpp

#include <iostream>
#include "bar.h"
int main() {
  Bar b;
  std::cout << b.s_foo.m_foo << std::endl;
}

This compiles fine when I specify foo.cpp before bar.cpp.

$ g++ -std=c++11 main.cpp foo.cpp bar.cpp -o main
$ ./main
Foo!

But if bar.cpp is compiled first, I get a segmentation fault.

$ g++ -std=c++11 main.cpp bar.cpp foo.cpp -o main  # note bar.cpp comes before foo.cpp here
$ ./main
Segmentation fault (core dumped)

Aucun commentaire:

Enregistrer un commentaire