C++ stack allocated object, explicit destructor call

大城市里の小女人 提交于 2019-12-03 15:56:20

clear() isn't guaranteed to actually release the allocated storage in the vector; _Tidy() in the MSVC implementation will actually free that storage, so this was probably done as an optimization.

It's an evil thing to do, but you can do it legally (without undefined behavior) so long as the storage is reused by an object of the same type (ignoring cv-qualifiers) that takes up exactly all of the storage:

T automatic;
automatic.T::~T();
new (&automatic) T();

Section 3.8.7 of the C++ standard describes this usage scenario and explains how it's legal; it even includes an example that is similar to the above.

Could this class use some kind of placement new method? That's the only time I tend to see explicit destructors in use.

Large vector?

Wild guess... when clear() is called the vector is usually emptied but the memory not released. That is why there's the pattern

std::vector<T>().swap(vector_to_clear);

to empty the vector for reuse and clear the allocated memory.

Perhaps the original author did not know the pattern and tried to get rid of the allocated memory in this wicked fashion. (I think _Tidy frees the allocated memory)

It's definitely not a good idea. Any operation on an object after the destructor starts running yields undefined behavior.

Maybe the original coder cared about where in memory the objects were allocated.

Then the destructor must be called explicitly, as per this discussion.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!