mardi 3 décembre 2019

C++ Why program with extern instance referenced before defined compiles and links

The problem can be shown on a simple example:

extern A<bool> a;
B b(a);
A<bool> a("a");

In header file:

template<typename T>
class A {
    public:
        A(const char * name) : m_name(name) {}

        const char * name() const {
            return m_name;
        }
        ...
        ...
    private:
        const char * m_name;
};

class B {
    public:
        B(A & a) {
            printf("%s = %p\n", a.name(), &a);
        }
};

The code actually compiles, links and produce:

(null) = 0044F604

I wonder if this shouldn't be caught by compiler and fail.

Compiler in question is gcc 9.2.0 (mingw-w64-i686).

Aucun commentaire:

Enregistrer un commentaire