析构函数参数
The article Are destructors overloadable? talks about overloading the destructor.
This raised a question: Can a destructor have parameters?
I've never used or seen a destructor with parameters. I could not come up with an example of a reason to use parameters to the destructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++0x 草案 n3290 的第 §12.4 节对析构函数有这样的说法:
(添加了强调)
所以不,析构函数不接受参数。 (2003 年标准的措辞与上段完全相同。)
Section §12.4 of C++0x draft n3290 has this to say about destructors:
(emphasis added)
So no, destructors do not take parameters. (The 2003 standard has the exact wording of the above paragraph.)
不,这是简单的答案。这将使自动资源管理成为一个重要的问题,因为你必须担心析构函数采用了哪些参数以及你将从哪里获取它们。如果发生异常,编译器如何知道要传递给析构函数的内容是什么?
No, is the simple answer. This would make automatic resource management a significant bitch, because you'd have to worry about what parameters the destructor took and where the hell you were going to get them from. What about in the case of exception- how would the compiler know what to pass your destructor?
不,反正你几乎不会直接打电话给他们,那有什么用呢?
析构函数应该销毁对象,仅此而已。
No. You hardly ever call them directly anyway, so what would be the use.
The destructor is supposed to destroy the object, nothing more.
我认为带参数的析构函数有时是有用的。
想想pmr。当我们使用 pmr 容器时,例如
std::pmr ::向量
。在每个std::pmr::string中,它都会存储一个指向pmr分配器的指针,但是,该指针存储在std::pmr::vector
中,我们不必将其存储在每个 std::pmr::string 中。如果我们可以将指针传递给 std::pmr::string 的析构函数,那么我们就不必存储它。目前,我们没有任何方法将参数传递给析构函数。顺便说一句,我们可以使用 offset 来获取参数(这种方式很难看,在实际中无法使用,如果有更好的方法,请告诉我)。这是一个示例。
I think a destructor with parameters is usable in sometimes.
Think about pmr. When we use pmr containers, for example,
std::pmr::vector<std::pmr::string>
. In everystd::pmr::string
, it will store a pointer to pmr allocator, however, the pointer is stored in thestd::pmr::vector
, we don't have to store it in everystd::pmr::string
. If we can pass the pointer tostd::pmr::string
's destructor, we don't have to store it.At current, we don't have any way to pass paramters to destructor. BTW, we can use offset to get parameter (this way is ugly and cannot be used in practice, if there are any better way, please let me know). Here is an example.