PIMPL、POD、实现类的可见性,它的析构函数会被调用吗?
维基百科声称,在 有关不透明指针的文章中,那个
d 指针是类的唯一私有数据成员,指向结构体的实例(该结构体必须是 POD,因为它的析构函数不可见)
这在 PIMPL 中不是必需的,而且维基百科通常是特殊的,不是吗? ?
我将缺少 d 指针标签作为我问题的答案,但希望有人可以为维基百科做出贡献和/或澄清事情。或者只是说维基百科很糟糕,最后的手段等等:)
我的问题是,当在 cpp 实现文件中完全声明和定义时,嵌套类的方法的可见性如何?它的析构函数会按预期被调用吗(包含类将在其析构函数中调用它的delete)?
Wikipedia claims, in the article on opaque pointers, that
The d-pointer is the only private data member of the class and points to an instance of a struct (which must be a POD since its destructor is not visible)
This is not required in PIMPL and just Wikipedia being typically idiosyncratic isn't it?
I'm taking the lack of d-pointer tag as an answer to my question, but hoping someone might contribute to Wikipedia and/or clarify things. Or just say Wikipedia is awful, last-resort etc :)
The point of my question is, how visible are a nested class's methods when fully declared and defined in the cpp implementation file? Will its destructor get called as expected (the containing class will call delete on it in its destructor)?
_EDIT_
Fixed version, http://en.wikipedia.org/wiki/Opaque_pointer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PIMPL 是一个令人厌恶的惯用语,我得出的结论是它更像是一种反模式。
但是,如果您坚持使用它,您可以在实现文件中简单地将析构函数定义为空,以充分利用您想要用来自动析构非 POD 实现的任何智能指针。
这个快速代码示例清楚地将维基百科定义为完全错误的 - 完全可以在实现文件中简单地定义析构函数来使用您想要的任何析构函数,甚至是需要完整定义的智能指针。
PIMPL is a disgusting idiom, and I've come to the conclusion that it's more of an anti-pattern.
However, should you insist on using it, you can trivially define the destructor as empty in an implementation file to make full use of any smart pointer you care to use to automatically destruct non-POD implementations.
This quick code sample clearly defines Wikipedia as completely wrong- it's more than possible to simply define the destructor in the implementation file to use whatever destructor you want, even smart pointers which require the full definition.
是的,这完全是错误的。 PIMPL 结构的析构函数在调用它的地方必须是可见的,这是来自类本身的析构函数的定义。将两个析构函数放在同一个 .cpp 文件中,首先是 PIMPL dtor,这样就可以保证可见性。
PIMPL dtor 没有理由在任何其他点可见,因为它没有在那里被调用。
Yup, it's plain wrong. The destructor of the PIMPL struct must be visible at the point where it's called, which is from the definition of the destructor of the class itself. Put both destructors in the same .cpp file, PIMPL dtor first, and visibility is assured.
There is no reason for the PIMPL dtor to be visible at any other point, since it's not called there.