C ++堆栈分配对象,显式析构函数调用 [英] C++ stack allocated object, explicit destructor call

查看:102
本文介绍了C ++堆栈分配对象,显式析构函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用现有库时遇到了一个奇怪的析构函数。堆栈分配的stl向量的析构函数被显式地调用,当它的对象可能需要被再次使用的情况。这些向量对象是具有专用 clear 方法的stl向量类的稍微定制的版本。在析构函数体中存在两个方法调用: clear() _Tidy()

I came across a strange use of the destructor while working on an existing library. The destructor of a stack allocated stl vector was being called explicitly, when its the case that that object may need to be used again. These vector objects are a slightly customised version of the stl vector class that have a specialized clear method. In the destructor body there exist two method calls: clear(), _Tidy().

我一直在想一个很好的理由,为什么这个析构函数被调用,而不是清除,但我在失去。任何人都清楚为什么这可能是个好主意。

I've been trying to think of a good reason why this destructor is being called rather than just clear but I'm at a loss. Anyone shed any light on why this may be a good idea?

推荐答案

clear存储在向量中;在MSVC实现中的_Tidy()将实际释放该存储,所以这可能是作为优化完成。

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.

这是一个邪恶的事情,但你可以合法(没有未定义的行为),只要存储由相同类型的对象(忽略cv-qualifiers)重用,该对象占用完全所有的存储:

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();

C ++标准的第3.8.7节描述了这种使用场景,它甚至包括与上述类似的示例。

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.

这篇关于C ++堆栈分配对象,显式析构函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆