简体   繁体   中英

Operator-Overloading in C++ (Copy-Constructor & Destructor)

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 "ab" (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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM