Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

an easier copy-assignment operator implement?

Tags:

c++

In C++ Primer 5th,13.2.1 Class That Act Like Values,the author make a class that act like a value, which means each object have its own copy of the resource that the class manage.The class is below, It is a very simple class, just contain a pointer to a string, and an int, member function are just default constructor and copy-control member.

class HasPtr{
    public:
    HasPtr(const std::string &s = std::string()) :ps(new std::string(s)), i(0){}
    HasPtr(const HasPtr &p) :ps(new std::string(*p.ps)), i(p.i){}
    HasPtr &operator=(const HasPtr &rhs);
    ~HasPtr(){ delete ps; }
    private:
        std::string *ps;
        int i;
};

Below is the implement of the operator= given by the book

HasPtr &HasPtr::operator=(const HasPtr &rhs){
    auto newp = new std::string(*rhs.ps);
    delete ps;
    ps = newp;
    i = *rhs.i;
    return *this;
}

This is good, but i think that we can use the following implement which can avoid delete pointer and allocate new memory.

HasPtr &HasPtr::operator=(const HasPtr &rhs){
    *ps = *rhs.ps;
    i = rhs.i;
    return *this;
}

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

like image 374
TungWah Avatar asked Sep 16 '26 17:09

TungWah


1 Answers

No, there is no problem in your code.

*ps

is itself a value type, so you can assign it directly. If you were making changes to improve the code, you might want to go further and change ps into a std::string instead of a std::string*. Then, you could eliminate the need for new and delete from the HasPtr class.

If

*ps

were instead a raw pointer to memory that class HasPtr manages, you would have to write code such as in the example from the book.

like image 189
Scott Langham Avatar answered Sep 18 '26 07:09

Scott Langham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!