Copy Control and resource management
• The class behaves like a value. means that it should have its own state, and when we copy a like-worthy object, the copy and the original object are completely independent, and changing the copy does not have any effect on the original object.
• Classes that behave like pointers share state. When we copy an object of this class, the copy and the original object use the same underlying data, and changing the copy also alters the original object.
13.2 Sessions
1#include <iostream>2#include <string>3 using namespacestd;4 5 classHasptr {6 Public:7Hasptr (Const string&s =string()): PS (New string(s)), I (0) {}8Hasptr (ConstHasptr &rhs): PS (New string(*rhs.ps)), I (RHS.I) {}9 TenHasptr &operator=(ConstHasptr &RHS); OneHasptr &operator=(Const string&RHS); A string&operator*(); - -~hasptr () {delete ps;} the Private: - string*PS; - inti; - }; + -Hasptr &hasptr::operator=(ConstHasptr &RHS) + { AAuto NEWP =New string(*rhs.ps); at Delete ps; -PS =NEWP; -i =rhs.i; - return* This; - } - inHasptr &hasptr::operator=(Const string&RHS) - { to*ps =RHS; + return* This; - } the * string& Hasptr::operator*() $ {Panax Notoginseng return*PS; - } the + intMain () A { theHasptr H ("Hi mom!"); + hasptr H2 (h); - hasptr H3 (h); $H2 ="Hi dad!"; $H3 ="Hi, son!"; -cout <<"h:"<< *h <<Endl; -cout <<"H2:"<< *H2 <<Endl; thecout <<"H3:"<< *h3 <<Endl; - return 0;Wuyi}
Operation Result:
Classes that behave like values
1#include <iostream>2#include <string>3 using namespacestd;4 5 classHasptr {6 Public:7Hasptr (Const string&s =string()): PS (New string(s)), I (0) {}8Hasptr (ConstHasptr &rhs): PS (New string(*rhs.ps)), I (RHS.I) {}9 Tenhasptr&operator=(ConstHasptr &RHS); One~hasptr () {delete ps;} A Private: - string*PS; - inti; the }; - -hasptr& hasptr::operator=(ConstHasptr &RHS) - { +Auto NEWP =New string(*rhs.ps); - Delete ps; +PS =NEWP; A return* This; at}
Defines a class that behaves like a pointer
1#include <iostream>2#include <string>3 using namespacestd;4 5 classHasptr {6 Public:7Hasptr (Const string&s =string()): PS (New string(s)), I (0), use (Newsize_t (1)) {}8Hasptr (ConstHasptr &rhs): PS (rhs.ps), I (RHS.I), use (rhs.use) {++*Use ;}9 TenHasptr &operator=(ConstHasptr &RHS); One~hasptr (); A - Private: - string*PS; the inti; -size_t *use;//used to record how many objects are members of a shared *ps - }; - +Hasptr &hasptr::operator=(ConstHasptr &RHS) - { +++*Rhs.use; A if(--*use = =0) at { - Delete ps; - delete use; - } -PS =rhs.ps; -i =rhs.i; inUse =Rhs.use; - return* This; to } + -hasptr::~hasptr () the { * if(--*use = =0) $ {Panax Notoginseng Delete ps; - delete use; the } +}
"C + + Primer the 13th chapter" 2. Copy Control and resource management