C++ Primer 5th notes (chap 13 copy control) rule of three and five

1. Three basic operations can control the copy operation of the class

• Copy constructor
• Copy assignment operator
• Destructor.

The new standard also has 2 functions:
• move constructor
• move-assignment operator

2. Two rules

Principle 1:

Usually the first 3 functions appear as a whole. When deciding whether a class should customize copy control members, a basic principle is to first determine whether the class needs a destructor. If a class needs a destructor, it is almost certain that it also needs a copy constructor and a copy assignment. Operator.

class HasPtr{
    
    
public:
	HasPtr(const std::string &s = std::string()):ps,(new std::string(s),i(0)){
    
    }
	~HasPtr(){
    
    delete ps;}
}

How to use the compiler will synthesize the default copy constructor and copy assignment operator, these functions will simply copy pointer members, which means that multiple HasPtr objects may point to the same memory (it will cause problems)

HasPtr f(HasPtr hp)	//HasPtr是一个传值参数,所以被拷贝
{
    
    
	HasPtr ret = hp;	//拷贝给指定的HasPtr
	return ret;	//ret 和 hp 被销毁
}

Principle 2

A class that needs a copy operation also needs an assignment operation, and vice versa, a copy constructor or copy assignment function does not necessarily need to be destructed.

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/113858381