|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
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? |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
Sergei Shelukhin wrote:
> 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? You should read the chapter parameter passing in C++ once more. You are returning a pointer to a local variable (the variable head goes out of scope when AddHead is left), so you cannot dereference this pointer anymore outside your function or you'll get Undefined Behaviour. Surely your compiler will give you a warning (at least VC6.0 does). Regards, Stuart |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
Hmm, thanks.
I rather got too used to GC patterns, if I still point at it, it should exist ![]() |
|
![]() |
| Outils de la discussion | |
|
|