C++ Primer 5th notes (chap 13 copy control) to prevent copying

For some classes, the copy operation is meaningless. For example, the iostream class prevents copying to prevent multiple objects from writing or reading the same IO buffer.

1. Deleted function

1.1 Definition

By adding the =delete function after the parameter list of the function to indicate that this is a delete function, that is, it cannot be called in any way.

struct Nocopy{
    
    
	NoCopy() = default;	//默认合成构造函数
	NoCopy(const NoCopy&) = delete;	//阻止拷贝
	NoCopy& operator=(const NoCopy&) = delete;	//阻止赋值
	~NoCopy() = default;	//默认合成析构函数
}
  • =delete must appear when the function is first declared, and the compiler needs to know that a function is deleted in order to disable it.
  • You can specify =delete for any function, but you can only use =default for functions with default composition.
  • The destructor cannot be a delete function, otherwise the delete object and the local object destructor will be error

1.2 The member function of the class is the effect of deleting the function

If the destructor of a member of the class is a delete function, then

  • The synthetic destructor of the class is also defined as a delete function
  • The synthetic copy constructor of the class is also defined as a delete function

If the assignment operator of a member of the class is a delete function, or the class has a const reference member, then

  • The composite copy assignment operator of the class is defined as deleted
  • Or there is a const member, it has no in-class initializer and does not explicitly define the default constructor, then the default constructor of the class is defined as deleted.

In short, if a class has data members that cannot be constructed, copied, copied, or destroyed by default, the corresponding member function will be defined as deleted.

2. Private copy control

Before the new standard, a class prevented copying by declaring its copy constructor and copy assignment operator to be private.

class PrivateCopy{
    
    
	PrivateCopy(const PrivateCopy &);
	PrivateCopy& operator= (const PrivateCopy &);
public:
	PrivateCopy();
	~PrivateCopy();
}

Guess you like

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