In C ++, can a static object survive its static member variable?

Regarding the order of destruction of static variables in C ++, are there any guarantees regarding the lifetime of static objects relative to their static member variables?

For example, if I had something like this (insanely simplified example for demo purposes only):

class Object {
    static std::vector< Object * > all_objects;

public
    Object() {
        all_objects.push_back( this );
    }

    ~Object() {
        all_objects.erase(
          std::remove(all_objects.begin(), all_objects.end(), this), 
          all_objects.end());
    }
};

Would it be “safe” for static objects in different compilation units? That is, is there any guarantee that the member variable all_objectswill adhere to at least as long as any valid object, or there may be a problem when it is all_objectsdestroyed until the last instance of the object?

, (, Python), main()?

+4
4

"" ?

. , all_objects static .

. , . / , .

- all_objects .

class Object {
    static std::vector<Object *>& get_all_objects();

public
    Object() {
        get_all_objects().push_back( this );
    }

    ~Object() {
       std::vector<Object *>& all_objects = get_all_objects();
       all_objects.erase(
          std::remove(all_objects.begin(), all_objects.end(), this), 
          all_objects.end());
    }
};

std::vector<Object *>& Object::get_all_objects()
{
    static std::vector<Object *> all_objects;
    return all_objects;
}

, ++ 11 Standard (3.6.3/1) .

, , .

, . all_objects Object.

+1

"" Objects ?

, .

, , . , .

. . .

, , , , , - - undefined undefined.

, (, Python), main()?

, , , . , , , ABI .. .

+1

, . .

, . , . return .

ob.h
class ob
{
  static int a;
  static int b;
public:
  ob()
  {
    a++;
  }
  ~ob()
  {
    b--;
  }
};

main.cpp   #include ob.h;

int ob::a = 0;
int ob::b = 0;

void tt()
{
  static ob zz;
}

int main() 
{
  static ob yy;
  tt();

  {
    ob b;
  }
  ob a;

  return 1;
}

vars , , . , A.dll B.dll, , , . lib dll, , . , . A 1.0, B - 1.2. , . . . , . , - .

, . , .

+1

@Niall, undefined, .

-, ( ).

, static "" , "" ( ):

class Object {
    static std::vector< Object * > all_objects;

public
    Object() {
        all_objects.push_back( this );
    }

    ~Object() {
        all_objects.erase(
          std::remove(all_objects.begin(), all_objects.end(), this), 
          all_objects.end());
    }
};

Object& static_obj()
{
     static Object obj;
     return obj;
}

std::vector< Object * > Object::all_objects; // It is created first (before main)

int main()
{
    Object& o = static_obj(); // `obj` is initialized here.
} // At the end of the program, `obj` will be destroid first.
0

Source: https://habr.com/ru/post/1654862/


All Articles