I’m trying to override the + operator for a type whose constructor involves calling new (that is, the constructor needs to dynamically allocate something else) and hence whose destructor involves calling delete. Somewhere, I’d like to be able to use something like:
T c = a + b;
My problem is that I obviously need to create an object of type T inside the + function. If I allocate a temporary instance of T on the stack inside the + function implementation to return by-copy, the destructor to this instance will get called as the + call exits and (or so I believe) before the assignment to c. So that’s not an option. My other option seems to be to use new and dereference the pointer returned by new when returning. It seems that the problem with this approach, however, is that the pointer will be inaccessible, and there will be no way to call delete on it.
So my question is…it can’t be that overloading operators on types that involve dynamic allocation is that rare. How do people generally handle such a situation?
You make sure T obeys The Rule of 3, and there are no worries.