Know what functions C++ silently writes and calls

The big three:

  • Copy constructor
  • Copy the assignment function operator=
  • The destructor

When we write a class like this:

class Empty
{
public:
private:};Copy the code

We might think that this class is empty and has no content. But, in fact, we’re wrong. When we declare a class like this, we get some functions that the compiler automatically declares for our class. They include:

class Empty
{
public:
    Empty() {... }// Default constructor
    Empty(constEmpty& rhs) {...... }// Copy constructor
    ~Empty() {... }// destructor

    Empty& operator= (constEmpty& rhs) {...... }// Copy Assignment operator
};
Copy the code

When these functions are called, they are created by the compiler. The Big Three functions are best defined at class time, because using the default functions is not as efficient as writing your own. And using default functions can lead to all kinds of problems.

 

Points to remember:

The compiler can secretly create the default constructor, copy constructor, copy Assignment operator, and destructor for class.

 

If you don’t want to use a function automatically generated by the compiler, you should explicitly reject it

All the functions the compiler creates for us are pubic, and to prevent these functions from being created, we need to declare them ourselves. If we don’t want them to be called by anyone, we can declare them as private functions and leave them undefined, so that when someone else calls them, an error will occur. But it’s not elegant. After all, we programmers write programs for elegance. So we can do this:

Place the copy constructor and copy Assignment operator in a base class specifically designed to prevent copying actions.

 

 

class Uncopyable
{
protected:
    Uncopyable() {};
    ~Uncopyable() {};
private:
    Uncopyable(const Uncopyable&);
    Uncopyable& operator= (const Uncopyable&);
};

class HomeForSale:private Uncopyable
{
    ...
};
Copy the code

By constructing a base class that allows the technology to be inherited by other classes, code reuse is increased, but multiple inheritance can often lead to problems. Therefore, we should make a choice according to the actual situation in the actual use.

 

Points to remember:

To override functionality that the compiler automatically (and implicitly) provides, you can declare the corresponding member function private and not implement it. Using a base class like Uncopyable is another option.