How to prevent an object being created on the heap

2019-01-08 13:54发布

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;

and only allow them to do this:

Foo myfooObject;

Does anyone have any ideas?

Cheers,

标签: c++ stack heap
9条回答
家丑人穷心不美
2楼-- · 2019-01-08 14:20

@Nick

This could be circumvented by creating a class that derives from or aggregates Foo. I think what I suggest (while not robust) would still work for derived and aggregating classes.

E.g:

struct MyStruct {
    Foo m_foo;
};

MyStruct* p = new MyStruct();

Here I have created an instance of 'Foo' on the heap, bypassing Foo's hidden new operator.

查看更多
老娘就宠你
3楼-- · 2019-01-08 14:21

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

(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 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.

查看更多
【Aperson】
4楼-- · 2019-01-08 14:27

You could declare it as an interface and control the implementation class more directly from your own code.

查看更多
相关推荐>>
5楼-- · 2019-01-08 14:30

this can be prevented by making constructors private and providing a static member to create an object in the stack

Class Foo
{
    private:
        Foo();
        Foo(Foo& );
    public:
        static Foo GenerateInstance() { 
            Foo a ; return a; 
        }
}

this will make creation of the object always in the stack.

查看更多
萌系小妹纸
6楼-- · 2019-01-08 14:31

Not sure if this offers any compile-time opportunities, but have you looked at overloading the 'new' operator for your class?

查看更多
Deceive 欺骗
7楼-- · 2019-01-08 14:31

You could declare a function called "operator new" inside the Foo class which would block the access to the normal form of new.

Is this the kind of behaviour you want ?

查看更多
登录 后发表回答