Observable behavior and undefined behavior — What happens if I don't call a destructor?

后端 未结 13 2657
滥情空心
滥情空心 2020-12-03 06:48

Note: I\'ve seen similar questions, but none of the answers are precise enough, so I\'m asking this myself.

This is a very nitpicky "language-lawye

13条回答
  •  伪装坚强ぢ
    2020-12-03 07:46

    My reading of this portion of the standard is:

    • You are allowed to reuse the storage for an object that has a non-trivial destructor without calling that destructor
    • If you do, the compiler is not allowed to call the destructor for you
    • If your program has logic that depends on the destructor being called, your program might break.

    Side effects here are simply changes in program state that result from calling the destructor. They will be things like updating reference counts, releasing locks, closing handles, stuff like that.

    'Depends on the side effects' means that another part of the program expects the reference count to be maintained correctly, locks to be released, handles closed and so on. If you make a practice of not calling destructors, you need to make sure your program logic does not depend on them having been called.

    Although 'forgetting' is not really relevant, the answer is no, destructors are just functions. The key difference is that under some circumstances they get called by the compiler ('implicitly') and this section of the standard defines a situation in which they will not.

    Your example does not really 'depend on the side effects'. It obviously calls the random function exactly 3 times and prints whatever value it calculates. You could change it so:

    • The struct maintains a reference count (ctor +1, dtor -1)
    • A factory function reuses objects and randomly calls the destructor or not
    • A client function 'depends on' the reference count being maintained correctly, by expecting it to be zero.

    Obviously, with this dependency the program would exhibit 'undefined behaviour' with respect to the reference count.

    Please note that 'undefined behaviour' does not have to be bad behaviour. It simply means 'behavior for which this International Standard imposes no requirements'.

    I really think there is a danger of overthinking what is fundamentally quite a simple concept. I can't quote any authority beyond the words that are here and the standard itself, which I find quite clear (but by all means tell me if I'm missing something).

提交回复
热议问题