0

Let's say that I have a class A:

class A
{
    private:
    int value;
    public:
    A(int value)
    {
        this->value=value;
    }
    A& operator= (A& obj)
    {
        value=obj.value;
    }
};

There is a problem if I use the contextual instantiation:

A obj;
obj=*new A(5);

This case the new object created is not deleted and I lose it's reference. So I could put in the operator= overloading function the instruction to delete the object which is right value of the assignment, but if I do this:

A obj1,obj2;
obj1=obj2;

So how to avoid to waste memory? There's a way?

@Oli Charlesworth : But then how are iterators implemented? For example in std::list if I say:

list<string> l;
// initialize the list elements
list<string>::iterator i=l.begin();

This is an assignment, is another object of kind list::iterator created?

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • Yes, you're making a copy of `list::iterator`. Iterators are designed to be copyable. If you want to learn more about how objects are created and destroyed, you can pick up [a good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – In silico Feb 12 '12 at 13:27
  • So the object created by l.begin() is lost? – Ramy Al Zuhouri Feb 12 '12 at 13:34

2 Answers2

7

Yes, the solution is to not do obj = *new A(5). Just do obj = A(5).


BTW, your copy-assignment operator should take its argument as a const ref.
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

It is a terrible idea to do:

obj=*new A(5);

which does not allow you to destroy the reference new A(5) anymore. Instead, initialize directly or by the assignment operator A& operator= (const A& other):

A obj(5);

A obj;
obj = A(5);

You should definitely learn about the "Rule of three" so that you won't end up with memory problems.

AndiDog
  • 68,631
  • 21
  • 159
  • 205