简体   繁体   中英

My const pointer array only returns nullptr before main starts, which interferes with the initialization of another class

So I'm working on a project that has two const arrays of two classes (classes A and B ). The class A array needs access to the class B array while initializing, but the B array always returns nullptr , which is a big problem. Perhaps it would be easier to see the code (heavily simplified because the actual classes are huge and most of the info is irrelevant here):

// A.h
#pragma once
#include <vector>
#include "B.h"
#include "B_ARRAY.h"

class A
{
private:
    int bOffset; // the array offset of the corresponding element in B_ARRAY
    std::vector<int> otherInfo; // other info, which determines the corresponding B_ARRAY element
public:
    A(std::vector<int> i) : otherInfo(i)
    {
        bOffset = -1;
        while (bOffset == -1)
        {
            // search algorithm for the corresponding element in B_ARRAY
        }
    }
    
    B* getB()
    { return B_ARRAY[bOffset]; }
}
// B.h
#pragma once
#include <vector>

class B
{
private:
    std::vector<int> info;
public:
    B(std::vector<int> i) : info(i)
    {}
    
    std::vector<into> getInfo()
    { return info; }
}
// B_ARRAY.h
#pragma once
#include "B.h"

const int B_LENGTH = 900;

B* const B_ARRAY[B_LENGTH] = 
{
    new B(std::vector<int>({...})),
    new B(std::vector<int>({...})),
    [...]
};
// A_ARRAY.h
#pragma once
#include "A.h"

const int A_LENGTH = 1200;

A* const A_ARRAY[A_LENGTH] = 
{
    new A(std::vector<int>({...})),
    new A(std::vector<int>({...})),
    [...]
};

While it's searching in the A constructor, B_ARRAY[x] is always nullptr , which makes B_ARRAY[x]->getInfo() fail. In main() , it works just fine, so I assume this means B_ARRAY isn't fully initializing until main() . What do I have to do to make sure it fully initializes before A_ARRAY ?

I could make a B object as a member of the A class, but a lot of A classes end up with identical B s (in my current code, I'd want them to reference the same B object), and both of the actual constructor calls are already long enough as it is, so splitting them over two arrays helps keep it organized.

See, for instance, Static variables initialisation order .

"C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes). But the order of initialization of variables is undefined across different compilation units."

So you can either initialize all the static vars in one source file, or restructure the code to not depend on that order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM