On 31.10.2015 21:46, Paul wrote:
> The code pasted below is a fairly standard implementation of a fairly
> standard problem -- finding the mth-to-last value in a linked list.
> I omitted the memory management aspects. I don't understand why the
> destructor is never called. For example, a local copy of the linked
> list is created in the constructList() function. I thought the
> destructor would be called when it goes out of scope.
>
> Thank you very much for your help.
Dynamically allocated object do not have a scope!
A pointer to linkedList does have a scope, but is is not
tidied to life of an objetc.
If you want to create a dynamic allocated object which life
is equal to the life of a pointer to this object, use smart
pointers. unique_ptr or shared_ptr (and then look to the
manual to see, how to construct pointers,; avoid new).
If you allocate something with new, you (in most cases)
have to delete is manually!
BTW, do not keep linked list as a pointer. You want to
wrap it into an object, a container. Then your container
have a destructor, where you can manually clean everything.
bartekltg
>
> Paul
>
> #include <cmath>
> #include <cstdio>
> #include <vector>
> #include <iostream>
> #include <algorithm>
> using namespace std;
>
> struct linkedList
> {
> int val;
> linkedList* next;
>
> linkedList(int Val):val(Val), next(0)
> {
>
> }
>
> ~linkedList()
> {
> cout << "destructor called"; // This never executes.
>
> }
>
> };
>
> // Construct a linked list from stdin
> const linkedList* constructList( )
> {
> linkedList* headList;
> linkedList* buildList;
>
> int listItems;
> bool first = true;
> while(cin >> listItems)
> {
> if(first)
> {
> build = new linkedList(listItems);