Today's interview encountered such a problem, requiring two classes to be written. One class can only be instantiated on the stack, and the other class can only be instantiated on the stack.
I have no idea how to solve this problem. After the interview is over, I have to solve it quickly. I am afraid I will forget it:
Can only be instantiated on the stack
The Destructor is set to a private or protected member. After the stack object is defined and the function ends, the non-public destructor cannot be called. In this case, destroy () {Delete this} should also be provided }, avoid Memory leakage.
Class cheaponly {public: cheaponly () {} void destroy () const {Delete this;} PRIVATE :~ Cheaponly (){}};
Can only be instantiated on the stack
Set the new Delete operator to a non-public access mode.
Class cstackonly {public: cstackonly (){}~ Cstackonly () {} PRIVATE: void * operator new (size_t size) {} void operator Delete (void * PTR ){}};
Summary: in fact, both of these questions are very simple, but they are controlled by the most basic access attributes of function members. However, during the interview, they suddenly cannot be remembered ~~~~
In addition, when I first came out of the interview, I suddenly thought of New delete. It was just a pitfall!