Overloading + Operator in C++ for a Dynamically Allocated Type
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 del开发者_高级运维ete
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.
If you create a temporary object on stack within operator+
, then on exit, depending on compiler and your operator implementation:
- The object will be passed via copy constructor to another temporary object, which will be passed to
c
via copy constructor again. OR - The object will be passed to
c
via copy constructor. OR - The temporary object will be actually
c
and there will be no copy constructor calls. (see http://en.wikipedia.org/wiki/Return_value_optimization)
As mentioned before, if you follow The Rule of 3 and provide correct implementation of copy constructor and assignment operator there won't be any problems under any circumstances, so you don't need to worry about actual implementation (unless you're crazy about performance). That's all about OOP.
std::string
and std::vector
are somehow able to do that, and your class is too. I don't suggest you learn their source code, it's quite intimidating. As another poster said, the rule of 3 is your friend. I can add that you should not call new
in your function. Allocate on the stack and return by value. C++ will do the necessary magic.
精彩评论