Servers by jDrones

Sitl instancing in code

First of all, im very sorry if this question is very basic, im just very curious about this and haven’t been able to find the answer yet.

so, ive been learning the singleton design pattern used in ardupilot source code. i learned it from its sitl implementation. one thing that disturbed me is that when i try to use the singleton design pattern, it returns an error and fortunately i know where it came from.

here’s the singleton design pattern i got (i’ll use the SITL.h and .cpp as an example as this is what i want to ask about):

// in SITL.h
namespace SITL{
class SITL
{
public:
    SITL(){
        printf("SITL INSTANTIATED!\n"); // debug string
        instance = this;
    }
    SITL (const SITL &other) = delete;
    SITL &operator=(const SITL&) = delete;
    
    static SITL *_singleton;
    static SITL *get_singleton(){ return _singleton; }

};
} // namespace SITL

namespace AP{
SITL *sitl();
};

// in SITL.cpp
namespace SITL{
SITL *SITL::_singleton = nullptr;
} // namespace SITL

namespace AP{
SITL::SITL *sitl(){
    return SITL::SITL::get_singleton();
}
};

we know that a class needs an instancing in order to be used so by default after creating a class we have to instantiate it “class_name instance_name”. however from what i see in all sitl’s code, i never found a single instantiation of the SITL class. what i found is every instatiation of SITL is a pointer, which isn’t an instatiation of a class. in another header file that includes SITL.h, they declare a pointer to SITL class as a that class member, and in the translation unit, the pointer is pointing to AP::sitl().

from what i know, AP::sitl() is pointing to NULL, so whenever another pointer of SITL class is pointing to AP::sitl() which is null, the pointer is also pointing to null thus we can’t use it. but if there are any function that creates SITL instance, every AP::sitl() will also point to that instance. the problem is, i never found it.

i tried printing a debug string in SITL() constructor, and when i run the SITL program, the debug string is printed even before the sitl setup (see picture).

my guess is that the AP::sitl() is instantiated explicitly. but still im very curious about this. where and when does the AP::sitl() instantiate?

thank you!

nevermind. i found it in plane / copter / other frame .cpp. this is so frustrating as ive been looking it for 2 days now. silly me, haha

Servers by jDrones