c++ - an easier copy-assignment operator implement? -


In C ++ primer 5th, 13.2.1 classes, which act like values, the author creates a class That works like value, it means that each object has its own copy of the resource, which classes manage. The square is down, this is a very simple class, just an indicator for a string, and an integer member member is the only default constructor and copy-control member.

HasPtr {public: HasPtr (const std :: string & amp; s = std :: string ()): ps (new std :: string (s)), i (0 } {} Hespant (Constable Hezpretre and P): PS (New Studd :: String (* P.P.)), I (P) {} Hampstrap and Operator = (Constant Hespect and PH); ~ HasPtr () {delete PS; } Private: std :: string * ps; Int i; };

The implementation of the operator given below = given by the book

  ispaffe and haspatr :: operator = (Constant Hespet & amp; rhs) {auto Newp = new std :: string (* rhs.ps); Delete ps; Ps = newp; I = * rhs.i; Return * This; }  

This is good, but I think we can use the following implementation that can avoid the removal of points and allocate new memory.

  HasPtr and HasPtr :: operator = (Constant Hespet & amp; RA) {* ps = * rhs.ps; I = rhs.i; Return * This; }  

I test my code, even self-assignment. However, is there any problem with this code?

No, there is no problem with your code.

So you want to move forward and change ps to std :: string instead of std :: string *. After that, you can eliminate the need for new and remove from the HasPtr class.

If

In the example, from the book, in the example.


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -