0

I think I am asking a question that might already have an answer here but I am afraid I was unable to figure it out from the linked page.

I am doing a linked list in c++, and scanning them from the start until the pointer to the next element in list is null. After some total garbage (this time used metaphorically) for an our I figured out I forgot to set the said pointer to the last element explicitely to NULL, because I was thinking an unset pointer is by default null.

I know, that unset values in C/++ cotains by default some garbage which causes troubles, like in this case, but I wonder is there a way to set them automatically to null, in case i forget to do so? I did not find much info in a web search.

Sorry if the question is rather rookie.

Community
  • 1
  • 1
Sean
  • 721
  • 5
  • 22

2 Answers2

3

You can use an always_initialized<T> template or in C++11 non-static data member initializers and uniform initialization.

// C++11:
struct Node {
    T value;
    Node* next = {};
};
// C++03:
template<typename T> struct always_initialized {
    T member;
    always_initialized(T t) : member(t) {}
    always_initialized() : member() {}
    // Copy operators and utilities 
};
struct Node {
    T value;
    always_initialized<Node*> next;
};

However in this specific case, it would be better to use unique_ptr<T> because it can automatically handle a lot more than just being null on default construction by default for you- it can also clean up your resources.

Puppy
  • 138,897
  • 33
  • 232
  • 446
  • thank you. i am selecting this as answer, because it seems to be the first and also mentions two methods. always_initialized and unique_ptr. – Sean Jan 23 '14 at 12:29
1

I highly recommend using std::unique_ptr, however you can always set it in your node's constructor :

struct Node {
    Node(T val) : value(val), next(NULLPTR) {}
    T value;
    Node * next;
};

....
last->next = new Node(val);

or C++11 version :

struct Node {
    T value;
    Node * next;
};

....
last->next = new Node{std::move(val), nullptr};
OneOfOne
  • 81,080
  • 16
  • 165
  • 166