Effective C + + clause 12: Do not forget every ingredient when copying an object

Source: Internet
Author: User

Remember:
The copy function should ensure that all member variables within the object and all parent components are copied.
Do not attempt to implement another copy function with one copy function. Common functions should be placed in a third function and called together by two copy functions.

The following is a class that implements its own copy function, together with normal.

voidLogcall (Const string&funcName);classCustomer { Public:    ... Customer (Constcustomer&RHS); Customer&operator=(Constcustomer&RHS); ...Private:    stringname;}; Customer::customer (Constcustomer&RHS): Name (rhs.name) {Logcall ("Customer Copy Constructor")}customer& Customer::operator=(Constcustomer&RHS) {Logcall ("Customer copy assignment operator"); Name=Rhs.name; return* This;}


But if you add a member variable for class, you must modify the copy function at the same time. If you forget, the compiler will not remind you.

class Date {...}; class Customer {public:    ... Private :     string name;    Date lasttransaction;} ;

In addition, if inheritance occurs, you should have the copy function of the subclass call the corresponding parent class function.

classPrioritycustomer: Publiccustomer{ Public:    ... Prioritycustomer (Constprioritycustomer&RHS); Prioritycustomer&operator=(Constprioritycustomer&RHS); ...Private:    intPriority ;}; Prioritycustomer::P Rioritycustomer (Constprioritycustomer&RHS): Customer (RHS), priority (Rhs.priority)//call the copy constructor of the parent class{Logcall ("Prioritycustomer Copy Constructor")}prioritycustomer& Prioritycustomer::operator=(Constprioritycustomer&RHS) {Logcall ("Prioritycustomer copy assignment operator"); Customer::operator= (RHS);//assigning the parent component to a valuePriority =rhs.priority; return* This;}






Effective C + + clause 12: Do not forget every ingredient when copying an object

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.