Is a C++ destructor guaranteed not to be called until the end of the block?

后端 未结 8 1953
孤街浪徒
孤街浪徒 2021-01-03 18:03

In the C++ code below, am I guaranteed that the ~obj() destructor will be called after the // More code executes? Or is the compiler allowed to destruct the

8条回答
  •  轮回少年
    2021-01-03 18:41

    Yes, it is guaranteed.

    The lifetime of an object with automatic storage duration ends at the end of its potential scope and not before. For such an object the potential scope begins at the point of declaration and ends at the end of the block in which it is declared. This is the moment when the destructor will be called.

    Note, that very pedantically speaking, even for an automatic object it is not correct to say it is destroyed when it "goes out of scope" (as opposed to "goes out of its potential scope"). The object can go out of scope and back into scope many times (if even more local objects with the same name are declared within the block), and going out of scope in such fashion does not cause the destruction of the object. It is the "very final end" of its scope that kills the automatic object, which is defined as the end of its potential scope as described above.

    In fact, the language standard does not even rely on the notion of scope to describe the lifetime of automatic objects (no need to deal with all these terminological intricacies). It just says that the object is destroyed at the exit of the block in which it is defined :)

提交回复
热议问题