Assignment Operator, Memory and Scope
Although I am using a garbage collector for this project, I've run into a couple of interesting situations that make me wonder just exactly what does C++ do when it leaves scope with regards to freeing memory or calling a class destructor. See the comments in the code.
It seems like C++ code has a bit of a conundrum with regards to passing class data around from function to function. If a class has internal data allocated via new in it's constructor, then the assignment operator should probably be overloaded to include allocating internal data again and copying it from the data available from the right hand side operand. Otherwise you run into bugs generated from having surprising multiple references to the same data.
/* MyClass has some internal variables allocated with new. This in theory allocates
a large buffer internally. */
MyClass *fp = new Myclass(1000000) ;
/* a convenient variable for referencing fp. Does fpref get deleted when
func1 returns and the destructor called invalidating the internal memory of *fp? */
MyClass &fpref = *fp ;
/* the () operator is overloaded */
fpref(7) = 8 ;
void func2(MyClass2 &x)
/* memory for v1 will be released and it's destructor called right?
But the assignment operator is a copying operator, copying all internal variables
after using new to create new data. Thus this creates a memory leak right? The original
class created in func1 via the new operator now has no reference */
MyClass v1 = func1() ;
/* MyClass2 has as one of it's members a MyClass object */
x.myclass = v1 ; // so we create yet another copy of v1
However this appears to create some problems. First it at times generates unnecessary copies of memory. If func1() returns a large object it appears that it gets copied twice for no particularly good reason. Moreover, doesn't it create a big memory leak on it's first assignment?
MyClass v1 = func1() ;
v1 gets copied from the output of func1() due to the assignment operators deep copy correct? Thus the original reference is lost.
I've also noticed for the compiler I'm using (MS visual studio 2008), that intellisense tagging doesn't work for pointers to classes. For example if I've overloaded the () operator, I'm not sure if something like
(*fp)(7) is legal code. However I'm concerned that if I create a reference to *fp, e.g. fpref, that it will get deleted and it's destructor called at the return of the function, thereby invalidating *fp's data.
Is it a true statement, therefore, that in order for me to avoid excessive copying or to prevent automatic freeing of my data, all references to a class must be carried in a pointer in a case like this? If so, a lot of syntax sugar (operator overloads) get's messed up.