Question: When overloading operators, I find myself needing to return an instance of an object, but I've run into some problems:
This won't work because the local object 'product' is destroyed at the end of the scope so the reference doesn't point anywhere useful
1 2 3 4 5 6
|
Foo& Foo::operator* (Foo& rhs)
{
Foo product(); // Default constructor
// do math
return product
}
|
This works, but there is a serious memory leak here since I lose my only pointer to the object and don't want to make the user of the class deal with memory management of this class
1 2 3 4 5 6
|
Foo& Foo::operator* (Foo& rhs)
{
Foo* product = new Foo();
// do math
return *product;
}
|
This also works as long as I custom-define a copy constructor, however that seems ineffecient
1 2 3 4 5 6
|
Foo Foo::operator* (Foo& rhs)
{
Foo product();
// do math
return product;
}
|
It seems ineffecient, because if I also want to make this an effective base class, I can't rely on operators (as those functions aren't inherited) so I'd do this to make operator definitions easy, but it invokes 2 copy constructors!
1 2 3 4 5 6 7 8 9 10 11
|
Foo Foo::multiply(Foo& rhs)
{
Foo product();
// do math
return product;
}
Foo Foo::operator*(Foo& rhs)
{
return multiply(rhs);
}
|
Is there a better way to do this?