13.5.2 define value type
Objects defined by classes with value semantics act like arithmetic objects, and vice versa. The string class is an example of a value type class.
The copy constructor no longer copies pointers. It will allocate a new int object and initialize the object to save the same value as the Copied object. Each object stores different copies of its own int value. Because each object saves its own copy, the Destructor will unconditionally Delete the pointer.
The value assignment operator does not need to assign a new object, but must remember to assign a new value to the object to which the Pointer Points, rather than assigning a value to the pointer.
The Pointer Points to the value instead of the pointer.
Class HasPtr
{
Public:
HasPtr (const int & p, int I): ptr (new int (p), val (I ){}
HasPtr (const HasPtr & orig): ptr (new int (* orig. ptr), val (orig. val ){}
HasPtr & operator = (const HasPtr &);
~ HasPtr (){
Delete ptr;
}
Int * get_ptr () const {return ptr ;}
Int get_int () const {return val ;}
Void set_ptr (int * p) {ptr = p ;}
Void set_int (int I) {val = I ;}
Int get_ptr_val () const {return * ptr ;}
Void set_ptr_val (int val) const {* ptr = val ;}
Private:
Int * ptr;
Int val;
};
HasPtr & HasPtr: operator = (const HasPtr & hasptr)
{
* Ptr = * hasptr. ptr;
Val = hasptr. val;
Return * this;
}
Even if you want to assign an object to itself. The value assignment operator must always be correct. In this example, operations are essentially safe even if the Left and Right operands are the same. Therefore, you do not need to explicitly check your own assignment.
From xufei96's column