Clause 06: if you do not want to use the function automatically generated by the compiler, you should explicitly reject it.

Source: Internet
Author: User

If you are a real estate developer, an intermediary software system naturally wants to have a class to describe a house.

Class homeforsale {...};

Every real estate developer will say that his house is unique, so it is not allowed for others to copy or assign values.

That is to say:

Homeforsale H1;

Homeforsale H2;

Homeforsale H3 (H1); // an attempt to copy H1 should not be compiled

H1 = h2; // an attempt to assign values to H1 should not be compiled

 

What should we do now?

If we do not define a copy constructor or a value assignment constructor, the compiler will generate it for us. What should we do at this moment?

 

There is a way to define the copy constructor or value assignment constructor as private.

But the problem arises. Although private, objects cannot be accessed, the friends and member functions of the class can be accessed. What should I do? We only declare not to define. In this way, if you use the copy constructor or value assignment constructor in a friend or member function, a connection error occurs.

Class homeforsales {

Public:

...

PRIVATE:

Homeforsales (const homeforsales &); // Why not write the name of the parameter?

Homeforsales & operator = (const homeforsales &);

}

Another question is, can we advance this error from the connection period to the compilation period?

Yes.

We can define such a class as a base class.

Class uncopyable {

Protected:

Uncopyable (){}

~ Uncopyable (){}

PRIVATE:

Uncopyable (const uncopyable &);

Uncopyable & operator = (const uncopyable &);

}

Class homeforsales: Public uncopyable {...}

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.