Copy-assignment operator

this code
1
2
3
4
5
  HasPtr &HasPtr::operator=(const HasPtr& obj){
	ps = new string(*obj.ps);
	i = obj.i;
	return *this;
}


same to this one, right?
1
2
3
4
5
6
7
 HasPtr& operator=(const HasPtr &hp) {
        std::string *new_ps = new std::string(*hp.ps);
        delete ps;
        ps = new_ps;
        i = hp.i;
        return *this;
    }
Last edited on
No, the first code does not use delete.
Last edited on
So better way would be just to copy like this:
1
2
3
4
5
HasPtr &HasPtr::operator=(const HasPtr& obj){
	ps = obj.ps;
	i = obj.i;
	return *this;
}
Probably not. If the old string that ps pointed to is no longer pointed to by any other pointer, it's lost, and you have a memory leak. But I can't say for sure because I don't know how your class is supposed to function.

Do you really have to use pointers here. Why not simply store a string variable?
Last edited on
I'm using pointer string because of exercise in book c++ primer. Otherwise I would use smart pointers... Tho I did try using the one with just copying pointer and I didn't get any memory leaks...

1
2
3
4
5
6
7
8
9
10
11
12
13
class HasPtr{
public:
	//copy obj, assignment obj, destructor
	HasPtr(const HasPtr &obj) : ps(new string(*obj.ps)), i(obj.i) { cout << "COPY OBJ" << endl; }
	HasPtr &operator=(const HasPtr&);
	~HasPtr(){ delete ps; cout << "DESTRUCTOR" << endl; }

	HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) {}
	void print() { cout << *ps << endl; }
private:
	std::string *ps;
	int	i;
};
Topic archived. No new replies allowed.