Limit object creation on heap and stack in C ++

I have a question about how to limit the creation of an object on a heap or stack? For example, how to make sure that the object does not live on the heap? How to make sure that the object does not live on the stack?

Thank!

+5
source share
4 answers

To prevent the object from being accidentally created on the heap, give it private operators new. For instance:

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, as well as provide friendly or static functions that perform the same functions. For example, here, which 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();
};
+12
source

( " " ), factory ( factory factory) .

( " " ), operator new . - , new.

, ? ?

+2

, . , , . , - :

void MyObject::destroy() const
{
   delete this;
}

, . ++ FAQ .

, , new private.

+1

It is easier to ensure the creation of an object on the heap. The operator newalways does this. It’s harder to make sure the object is on the stack. For small objects, creating an object of type MyType aObj;always uses the stack. For objects whose classes take up huge amounts of memory, the compiler may not use the stack.

0
source

All Articles