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

后端 未结 13 2656
滥情空心
滥情空心 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:30

    Say you have a class that acquires a lock in its constructor and then releases the lock in its destructor. Releasing the lock is a side affect of calling the destructor.

    Now, it's your job to ensure that the destructor is called. Typically this is done by calling delete, but you can also call it directly, and this is usually done if you've allocated an object using placement new.

    In your example you've allocate 2 MakeRandom instances, but only called the destructor on one of them. If it were were managing some resource (like a file ) then you'd have a resource leak.

    So, to answer your question, yes, forgetting to call a destructor is different to forgetting to call an ordinary function. A destructor is the inverse of the constructor. You're required to call the constructor, and so you're required to call the destructor in order to "unwind" anything done by the destructor. This isn't the case with an "ordinary" function.

提交回复
热议问题