I am learning about smart pointers and tried implementing in a linked list.the code of the node, List and main files are as follows:
Node.h
#pragma once
#include
class Node {
int data;
std::shared_ptr next;
public:
Node(int);
int getValue();
void setValue(int);
std::shared_ptr Next();
};
Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node(int value) : data(value){}
int Node::getValue(){
return data;
}
void Node::setValue(int value){
data = value;
}
std::shared_ptr Node::Next(){
return next;
}
List.h
class List{
std::shared_ptr head;
public:
//List();
bool isEmpty();
void insertNode(int value);
void printList();
};
List.cpp
#include "stdafx.h"
#include "List.h"
#include
bool List::isEmpty(){
return (head == nullptr) ? true : false;
}
void List::insertNode(int value){
Node newNode(value);
if (isEmpty()){
head = std::make_shared(newNode);
}
else{
newNode.Next()=head; //Problem here
head = std::make_shared(newNode);
}
}
void List::printList(){
while (head->Next() != nullptr){
std::cout << head->getValue();
}
std::cout << head->getValue();
}
main.cpp
#include "stdafx.h"
#include "List.h"
#include
int _tmain(int argc, _TCHAR* argv[])
{
List newSingleList;
if (newSingleList.isEmpty())
std::cout << "The list is curently empty\n";
newSingleList.insertNode(10);
newSingleList.insertNode(20);
newSingleList.printList();
return 0;
}
The problem is that the value in the List.cpp file at "the commented line"
the debugger shows that even after the assignment the value is empty and the
node actually points to nothing. then the head in the next line is set to the
new node which then basically points to a different memory address without linking to the previous Node .
Why is this ? what am I missing ?
Here is the debugger snapshot: as said the next points to empty after stepover the breakpoint. according to the code the statement at the breakpoint must assign the next pointer to the previous head/node.
https://www.dropbox.com/s/yaybpukacx53fq1/Screenshot%202015-03-08%2011.33.08.png?dl=0
No comments:
Post a Comment