Arii
Arii

Reputation: 401

Recursive List: Everything calling destructor

So I'm trying to make a recursive linked list. It looks a bit like this:

class List  
{   int cur; //For now 
    List* nxt;

public:
    List()
        {cur = nullptr; nxt = nullptr;}
    ~List()
        {std::cout << "Destroyed\n";}

...

Now I have a function cons,

List cons(const int &a)
{   if(cur == nullptr)
    {   cur = new int;
        *cur = a;
    }
    else
    {   List* x = new List;
        x->cur = new int;
        *(x->cur) = *cur;
        x->nxt = nxt;
        *cur = a;
        nxt = x;
    }
    return *this;
}

And an operator,

std::ostream& operator<<(std::ostream& out, const List &b)
{   out << "Output\n";
    return out;
}

I'm using this code in main to drive it:

int main()
{   List a;
    std::cout << "Cons\n";
    a.cons(3);
    std::cout << "Cons\n";
    a.cons(2);
    std::cout << "Cons\n";
    a.cons(1);
    std::cout << a;
}

This, when ran, results in:

Cons
Destroyed
Cons
Destroyed
Cons
Destroyed
Out
Destroyed
Destroyed

My questions are,
a, why is it calling a destructor inside a member function,
b, why is it calling a destructor on a const reference,
and c, how the hell do destructors work and how do I stop mine from constantly killing itself?

Cheers.

Upvotes: 0

Views: 40

Answers (1)

Ivaylo Valchev
Ivaylo Valchev

Reputation: 10425

The function List cons(const int &a) returns a copy of *this. This results in a bunch of temporary List objects.

The destructor calls you are seeing are for the copies returned from each call to cons.

Tip: Use List& cons(int a) instead.

Upvotes: 1

Related Questions