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条回答
beautiful°
2楼-- · 2019-01-08 14:32

I don't know how to do it reliably and in a portable way.. but..

If the object is on the stack then you might be able to assert within the constructor that the value of 'this' is always close to stack pointer. There's a good chance that the object will be on the stack if this is the case.

I believe that not all platforms implement their stacks in the same direction, so you might want to do a one-off test when the app starts to verify which way the stack grows.. Or do some fudge:

FooClass::FooClass() {
    char dummy;
    ptrdiff_t displacement = &dummy - reinterpret_cast<char*>(this);
    if (displacement > 10000 || displacement < -10000) {
        throw "Not on the stack - maybe..";
    }
}
查看更多
Explosion°爆炸
3楼-- · 2019-01-08 14:45

Because debug headers can override the operator new signature, it is best to use the ... signatures as a complete remedy:

private:
void* operator new(size_t, ...) = delete;
void* operator new[](size_t, ...) = delete;
查看更多
Rolldiameter
4楼-- · 2019-01-08 14:46

You could overload new for Foo and make it private. This would mean that the compiler would moan... unless you're creating an instance of Foo on the heap from within Foo. To catch this case, you could simply not write Foo's new method and then the linker would moan about undefined symbols.

class Foo {
private:
  void* operator new(size_t size);
};

PS. Yes, I know this can be circumvented easily. I'm really not recommending it - I think it's a bad idea - I was just answering the question! ;-)

查看更多
登录 后发表回答