如何防止在堆上创建对象? [英] How to prevent an object being created on the heap?

查看:92
本文介绍了如何防止在堆上创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何在与平台无关的C ++代码中阻止在堆上创建对象吗?也就是说,对于 Foo类,我想阻止用户这样做:

Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:

Foo *ptr = new Foo;

,只允许他们这样做:

Foo myfooObject;

有人有什么想法吗?

干杯,

推荐答案

,但是它是不完整的,因为您实际上需要重载:

Nick's answer is a good starting point, but incomplete, as you actually need to overload:

private:
    void* operator new(size_t);          // standard new
    void* operator new(size_t, void*);   // placement new
    void* operator new[](size_t);        // array new
    void* operator new[](size_t, void*); // placement array new

(良好的编码习惯会建议您也应使delete和delete []重载运算符-我愿意,但是由于不会被调用,所以真的是不必要的。)

(Good coding practice would suggest you should also overload the delete and delete[] operators -- I would, but since they're not going to get called it isn't really necessary.)

Pauldoo 也是正确的,因为它无法生存聚集在Foo上,尽管它确实可以从Foo继承下来。您可以做一些模板元编程魔术来帮助防止这种情况,但是它对邪恶的用户是不能幸免的,因此可能不值得这样做。大约100%的方法是唯一使用方法的文档,并进行代码检查以确保正确使用它。

Pauldoo is also correct that this doesn't survive aggregating on Foo, although it does survive inheriting from Foo. You could do some template meta-programming magic to HELP prevent this, but it would not be immune to "evil users" and thus is probably not worth the complication. Documentation of how it should be used, and code review to ensure it is used properly, are the only ~100% way.

这篇关于如何防止在堆上创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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