Classes that can only be instantiated on stacks or stacks

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.