Mail Archives: djgpp/1997/10/21/01:31:51
Jason Nye <jnye AT nbnet DOT nb DOT ca> writes:
> I have figured out what was going on with my SIGSEGV!!!
>
> I created a class, say A, which had a helper class, say B. B was
> basically a singleton (except its
> members were not static), which means that there would only ever be one
> instance of this class. This
> class, B, would be hidden to the user of class A, therefore, I decided
> to put it in the cpp file. I also
> instantiated the class in the cpp file like so:
>
> #include <A.hpp>
>
> // B's interface is of no interest to the user of A
> class B {
> public:
> B(int size);
> ...
> };
>
> // B's functions...
> B::B(int size)
> {
> ...
> }
> ...
>
> // Create a static instance of B.
> static B workerB(100);
>
> // A's interface is defined in A.hpp
> A::A(char c)
> {
> //
> // Start using workerB as a helper here...
> }
>
Are you sure that A's constructor is not called before constructor
of workerB? Say, by having "static A someobject;" somewhere.
Suggestion: place cerr << __PRETTY_FUNCTION__ << endl;
in constructors of A and B and see which one comes first.
> ---------------------------------------------------------------------
>
> Now, I would think that this would work absolutely fine, but what
> actually happens is once the execution has gone past the construction of
> workerB, all Hell breaks loose. This, apparently is a bug and a damn
> hard to find bug at that. I also tried declaring workerB without the
> static storage class and it crashed that way too.
>
> This is how I got around the bug:
> ---------------------------------------------------------------------
>
> // Header:
> #ifndef A_HPP
> #define A_HPP
>
> class B;
>
> class A {
> public:
> A::A(char c);
> private:
> static B *workerB;
> static bool setup;
> };
>
> #endif
> ---------------------------------------------------------------------
>
> // Cpp:
> #include <A.hpp>
>
B* A::workerB = 0;
> bool A::setup = false;
>
> // B's declaration as above...
> ...
>
> A::A(char c)
> {
> if (!setup) {
> workerB = new B(100);
> setup = true;
> }
> }
> ----------------------------------------------------------------------
>
> This works with no crashes. Why did the other way not work? I have no
> Idea. Maybe someone could help me out on why the static initialization
> did not work.
- Raw text -