Suppose one has this code:
class MyClass {
public:
MyClass(int foo) : foo(foo){}
private:
int foo;
//overloaded operator +
public:
MyClass operator+(MyClass &mc){
MyClass c(mc.foo + foo);
return c;
}
};
int main(int argc, char* argv[]){
MyClass c1(10);
MyClass c2(12);
c2 = c1 + c2;
return EXIT_SUCCESS;
}
Where the operator + is overload such that it does not modify the object but create a new object and return it.
When c2 = c1 + c2 is called, c2 is bound with the new object, but the previous object bound with c2 is not (or at least it seems to me) freed. I’m i right?
Since C++ has no a Garbage Collector, is this a problem?
Am I missing something?
No, that’s not what happens.
There is no “previous object bound with
c2“;c2is not a reference to an object, it is the object.c2‘s lifetime begins when it is declared and ends when it goes out of scope.The assignment operator doesn’t rebind
c2(which would be meaningless —c2isn’t a java-style reference!), it assigns to it. Specifically, it invokesc2.operator=(MyClass)orc2.operator=(const MyClass&).c2existed before the assignment, and the same object continues to exist after the assignment.