简体   繁体   中英

C++ operator overloads and destructors

struct Node
{
int value
Node* next;
}
typedef List Node*

const Set operator +(const Set& a, const Set& b)
{
    Set aSet;
    List newList = mergeListsCopy(a.list, b.list);
    aSet.list = newList;
    return aSet;
}

class Set
{
public:
//method decs
private:
    List list;
};

Set::~Set()
{
    list = deleteList(list);    
}

The internals of this code work perfectly fine, mergeListsCopy creates a new list from two singly linked lists and assignes the pointer to the list which is a private variable of aSet.

The problem is when aSet is returned, aSet.list is some strange poison address( in this case 0xf).

When I ran it through the debugger a Set was created in the scope of the operator overload and but two references to this set were also created locally both using the symbol aSet, before the return occurred, the program jumped to the destructor, presumably for the extraneous Set, but since there is only one Set it gets destroyed.

When I comment out my destructor this problem goes away. What did I do wrong?

You need to follow the Rule of Three .

If you need to explicitly declare either the destructor , copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

It is most likely that temporary nameless objects get created(by calling the implicit compiler generated copy constructor) during the course of execution of your program and when those temporary objects get destroyed by call to destructor it ends up messing your linked list.

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