Reputation: 39
When I run the following code in C++:
#include <iostream>
using namespace std;
class Test
{
public:
string name;
Test();
Test(string pname);
~Test();
Test operator+(Test right);
};
Test Test::operator+(Test right)
{
Test neo_name;
neo_name.name = name + "-" + right.name;
return neo_name;
}
Test::Test()
{
}
Test::Test(string pname)
{
name = pname;
}
Test::~Test()
{
cout << "~ " << name << endl;
}
int main()
{
Test D1("a");
Test D2("b");
Test D3;
D3 = D1 + D2;
return 0;
}
I notice that the +
operator overload method destroys the "a-b" (neo_name) and "b" (right) objects.
(1) ~ a-b
(2) ~ b
(3) ~ a-b
(4) ~ b
(5) ~ a
Does anyone know how to destroy each object once?
At the end, I expect an output like:
(3) ~ a-b
(4) ~ b
(5) ~ a
Thanks!
Upvotes: 3
Views: 192
Reputation: 9078
You have a few places you can clean up.
Change to this:
Test operator+(const Test & right);
Your current implementation requires an unnecessary copy.
Next, when calling your operator+ method:
Test D3 = D1 + D2;
There's a basic rule that you should almost always initialize when you instantiate. Think about what has to happen.
If you do this:
Test D3;
D3 = D1 + D2;
Then you're going to construct a default D3 and then in the very next line, you call your operator+ and then copy over D3. But if you do it all on one line, the compiler can be smarter, quite a bit smarter, actually.
Try those changes and see if you're happier.
Upvotes: 1