Sobes.tech
Junior — Middle

How can the creation of class instances in dynamic memory be prohibited?

sobes.tech AI

Answer from AI

To prevent creating instances of a class in dynamic memory (using new), you can make the new operator private or delete its declaration.

Example in C++:

class MyClass {
public:
    MyClass() {}
    // prohibit creation in dynamic memory
    void* operator new(size_t) = delete;
    void operator delete(void*) = delete;
};

int main() {
    MyClass obj; // OK, on the stack
    // MyClass* p = new MyClass(); // Compilation error
}

Thus, objects can only be created on the stack or as static, but not through new.