有什么办法可以防止类的动态分配吗?

发布于 2024-11-14 01:32:41 字数 535 浏览 2 评论 0原文

我在嵌入式系统中使用 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

将军与妓 2024-11-21 01:32:41

您可以像毒害复制构造函数一样毒害operator new。只是一定要确保不要毒害新的安置。虚拟析构函数仍然是一个不错的推荐。

int main() {
    char data[sizeof(Derived)];
    if (condition)
        new (data) Derived();
    else
        new (data) Base();
    Base* ptr = reinterpret_cast<Base*>(&data[0]);
    ptr->~Base();
}

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.

int main() {
    char data[sizeof(Derived)];
    if (condition)
        new (data) Derived();
    else
        new (data) Base();
    Base* ptr = reinterpret_cast<Base*>(&data[0]);
    ptr->~Base();
}
沙沙粒小 2024-11-21 01:32:41
class A
{
private:
    void *operator new(size_t);
    ...
};

省略号用于 operator new 的其他重写以及类的其余部分。

class A
{
private:
    void *operator new(size_t);
    ...
};

The elipses are for the other overrides of operator new and the rest of the class.

如痴如狂 2024-11-21 01:32:41

只需将操作员 new 设为私有即可

Just make operator new private

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文