Inline variables lifetime

Viewed 58

Do inline variables have some defined initialization/destruction order like regular non-static class members, for example?

Assume I have inline variable b that depends on inline variable a:

#include <memory>
#include <iostream>

struct A
{
    A() : p(std::make_shared<int>(5)) {}

    std::shared_ptr<int> p;
};

struct B
{
    B(A& a) : p(a.p.get()) { func(); }

    ~B() { func(); }

    void func() { std::cout << *p; }

    int* p;
};

inline A a;
inline B b(a);

int main()
{
    return 0;
}

My understanding was that a and b should not be instantiated, because they are not referenced, but surprisingly this code prints 55 with both MSVC2022 and GCC12. And even if I do this:

class C
{
public:

    static inline A a;
    static inline B b = B(a);
};

I get the same result.

  1. Is it guaranteed that b is created after a and is destroyed before a?

  2. Are inline variables always instantiated even if they are not referenced?

  3. What if I remove inline in the first code sample? What changes?

  4. What will happen if a and b are in different translation units?

0 Answers
Related