I have a question about how to limit the creation of object on heap or stack? For example, how 开发者_如何学Cto make sure an object not living on heap? how to make sure an object not living on stack?
Thanks!
To prevent accidental creation of an object on the heap, give it private operators new. For example:
class X {
private:
void *operator new(size_t);
void *operator new[](size_t);
};
To prevent accidental creation on the stack, make all constructors private, and/or make the destructor private, and provide friend or static functions that perform the same functionality. For example, here's one that does both:
class X {
public:
static X *New() {return new X;}
static X *New(int i) {return new X(i);}
void Delete(X *x) {delete x;}
private:
X();
X(int i);
~X();
};
To prevent an object from being allocated on the stack define a private destructor. This results in a compilation error for a stack based object, as it prohibits the implicit destructor call when a stack based object goes out of scope. You will need to implement a public destroy method, something along the lines of:
void MyObject::destroy() const
{
delete this;
}
to clean up your object that is allocated on the heap. Make sure to read the C++ FAQ for some caveats.
Similarly, to prevent an object from being allocated on the heap, make sure to define the new
operator private.
You can prevent an object being declared with automatic duration ("on the stack") by making its constructor private and providing a factory (abstract factory or factory method) to control creation of new objects.
You could try to prevent an object being allocated dynamically ("on the heap") by making its operator new
private. However this doesn't prevent someone from creating an instance of your class using placement new
.
Why would you want to control how your object is allocated? What problem are you trying to solve?
It's easier to ensure the object is created on the heap. The new
operator always does that.
It is more difficult to ensure that the object is on the stack. For small objects, creating an object like MyType aObj;
always uses the stack. For objects whose classes occupy huge amounts of memory, the compiler might not use the stack.
精彩评论