Learn C++ 3: Disallow C++ class copy and assignment
I came across the two lines below. At the beginning, I thought they are declaration for a customized destructor. It turned out that I’m wrong after a discussion with my colleague.
net_infer(const net_infer&) = delete;
net_infer& operator=(const net_infer&) = delete;
1. Disallow copy
a. net_infer: This is the name of the class.
b. const net_infer&: This is a reference to a const object of type net_infer. It’s the parameter type of the copy constructor.
c. = delete: This part of the declaration explicitly deletes the copy constructor. It means that attempts to create copies of net_infer objects using the copy constructor will result in a compilation error.
2. Disallow assignment
a. net_infer&: This specifies the return type of the copy assignment operator. It returns a reference to a net_infer object.
b. operator=: This is the name of the copy assignment operator.
c. (const net_infer&): This specifies the parameter of the copy assignment operator, which is a reference to a const object of type net_infer. This parameter represents the object that is being assigned from.
d. = delete: This part of the declaration explicitly deletes the copy assignment operator. It means that attempts to assign one net_infer object to another using the copy assignment operator will result in a compilation error.
By deleting the copy assignment operator or the copy constructor, the class net_infer effectively disallows assignment operations and copy between its instances. This is useful in cases where copying or assigning instances of the class would lead to undesirable behavior, such as resource leaks or invalid state changes.
Enjoy Reading This Article?
Here are some more articles you might like to read next: