OK you bring up some interesting points here. I could have used vector as the baseline array inside my class. One reason why I didn't is that the garbage collector I'm using would not be aware of vector. The other reason is that performance is critical and I need to be able to pass raw pointers to arrays to low level C code.
If what you all are telling me is correct, the default copy and assignment operators will call the class specific assignment and copy operators if my class contains members who are classes or containers themselves (e.g. std::vector<T>).
It's still odd to me that if a function returns a reference to a class created with new, you could so easily create a memory leak. If you write code to overload the assignment operator (=), does the left hand side call the default constructor to initialize itself first. ie in a statement of the form
Code:
MyClass v1 = func1() ;
where func1() returns a reference to MyClass.
If I define the overload function
Code:
class MyClass {
public:
double *arr ;
.....
MyClass& MyClass::operator=(const MyClass &rhs) {
/* is *this created by a call to the default constructor
MyClass() ? */
// Only do assignment if RHS is a different object from this.
if (this != &rhs) {
if (this->arr == NULL) {
// uninitialized case, just do a shallow copy
} else {
... // Deallocate, allocate new space, copy values...
}
}
return *this;
}
My thought would be to detect the case wherein the variables in MyClass are uninitialized by forcing the default or no argument constructor to null out the pointers. This would then allow me to test for this case and to do a shallow copy in this case. If I think about it, almost all my uses of = are for initializing new class variables.
Wait a minute. I think this is unnecessary as well. If I understand what you've told me, then a declaration of the form
Code:
MyClass &v1 = func1() ;
will have the effect of not calling the constructor, copy assignment or even the destructor for v1 ! If I use a garbage collector, then the memory leak created by not destroying v1 will be removed anyway.