I am a beginner with C ++. And I do the exercises in C ++ Primer (5th Edition). I found a link to Exercise 13.8 from Github ( here ), which is shown below.
using std::cout;
using std::endl;
class HasPtr {
public:
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { }
HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i) { }
HasPtr& operator=(const HasPtr &hp) {
std::string *new_ps = new std::string(*hp.ps);
delete ps;
ps = new_ps;
i = hp.i;
return *this;
}
void print() {
cout << *(this->ps) << endl;
cout << this->i << endl;
}
private:
std::string *ps;
int i;
};
int main() {
HasPtr hp1("hello"), hp2("world");
hp1.print();
hp1 = hp2;
cout << "After the assignment:" << endl;
hp1.print();
}
What scares me is the function HasPtr& operator=(const HasPtr &hp). I don’t know why here delete ps;. I thought this was a mistake, but it worked when I compiled the code. However, it also works when I delete a line delete ps;. So, I do not know if delete ps;and what is the advantage if it is reserved.
source
share