有什么办法可以防止类的动态分配吗?
我在嵌入式系统中使用 C++ 基类和子类(为了清楚起见,我们将它们称为 A 和 B)。
它对时间和空间都很关键,所以我真的需要它是最小的。
编译器抱怨缺少虚拟析构函数,我理解这一点,因为如果您分配 B*
然后将指针作为 A*
的实例删除,这会给您带来麻烦代码>.
但我永远不会分配此类的任何实例。有没有一种方法可以重载operator new()
,以便在任何一个类都没有动态分配的情况下它可以编译,但如果最终用户尝试分配 A 或 B 的新实例,则会导致编译器错误?
我正在寻找一种与通过私有构造函数“中毒”自动编译器复制构造函数的常见技术类似的方法。 (例如 http://channel9.msdn.com/Forums/ TechOff/252214-私有复制构造函数和私有运算符-C)
I'm using a C++ base class and subclasses (let's call them A and B for the sake of clarity) in my embedded system.
It's time- and space-critical, so I really need it to be kind of minimal.
The compiler complains about lack of a virtual destructor, which I understand, because that can get you into trouble if you allocate a B*
and later delete the pointer as an instance of A*
.
But I'm never going to allocate any instances of this class. Is there a way I can overload operator new()
such that it compiles if there's no dynamic allocation of either class, but causes a compiler error if an end user tries to allocate new instances of A or B?
I'm looking for a similar approach to the common technique of "poisoning" automatic compiler copy constructors via private constructors. (e.g. http://channel9.msdn.com/Forums/TechOff/252214-Private-copy-constructor-and-private-operator-C)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以像毒害复制构造函数一样毒害
operator new
。只是一定要确保不要毒害新的安置。虚拟析构函数仍然是一个不错的推荐。You can poison
operator new
in just the same way as you can a copy constructor. Just be sure not to poison placement new. A virtual destructor would still be a fine recommendation.省略号用于
operator new
的其他重写以及类的其余部分。The elipses are for the other overrides of
operator new
and the rest of the class.只需将操作员 new 设为私有即可
Just make operator new private