S
Sergei Shelukhin
Hi. I have barely written any C++ for past 3-4 years, I need to
refresh it in my memory so I decided to do some coding starting with
classic algos and data structures, using Visual Studio 9, unmanaged
code. Everything is humming, but I have the following problem I cannot
figure out. Say we have the following:
template <typename T> class SLL
{
public:
SLL<T>* AddHead(T value);
T value;
SLL<T>* next;
};
....
SLL<int>* sll = new SLL<int>;
sll->next = NULL; //yeah I know I also need a constructor
sll->value = 1;
sll = sll ->AddHead(0);
sll = sll ->AddHead(0);
If I use this implementation of AddHead:
SLL<T>* head = new SLL<T>;
head->value = value;
head->next = this;
return head;
everything is ok;
If I use this,
SLL<T> head;
head.value = value;
head.next = this;
return &head;
the first call is ok; before the second call "sll" points to memory
location X and contains the list of two elements; but inside the
second call "this" points to X that has uninitialized instance in it
with random value and next pointing into nowhere.
How come?
refresh it in my memory so I decided to do some coding starting with
classic algos and data structures, using Visual Studio 9, unmanaged
code. Everything is humming, but I have the following problem I cannot
figure out. Say we have the following:
template <typename T> class SLL
{
public:
SLL<T>* AddHead(T value);
T value;
SLL<T>* next;
};
....
SLL<int>* sll = new SLL<int>;
sll->next = NULL; //yeah I know I also need a constructor
sll->value = 1;
sll = sll ->AddHead(0);
sll = sll ->AddHead(0);
If I use this implementation of AddHead:
SLL<T>* head = new SLL<T>;
head->value = value;
head->next = this;
return head;
everything is ok;
If I use this,
SLL<T> head;
head.value = value;
head.next = this;
return &head;
the first call is ok; before the second call "sll" points to memory
location X and contains the list of two elements; but inside the
second call "this" points to X that has uninitialized instance in it
with random value and next pointing into nowhere.
How come?