我正在学习智能指针并尝试在链表中实现。节点,List和主要文件的代码如下:
节点.h
#pragma once
#include <memory>
class Node {
int data;
std::shared_ptr<Node> next;
public:
Node(int);
int getValue();
void setValue(int);
std::shared_ptr<Node> Next();
};
节点.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> Node::Next(){
return next;
}
列表.h
class List{
std::shared_ptr<Node> head;
public:
//List();
bool isEmpty();
void insertNode(int value);
void printList();
};
列表.cpp
#include "stdafx.h"
#include "List.h"
#include <iostream>
bool List::isEmpty(){
return (head == nullptr) ? true : false;
}
void List::insertNode(int value){
Node newNode(value);
if (isEmpty()){
head = std::make_shared<Node>(newNode);
}
else{
newNode.Next()=head; //Problem here
head = std::make_shared<Node>(newNode);
}
}
void List::printList(){
while (head->Next() != nullptr){
std::cout << head->getValue();
}
std::cout << head->getValue();
}
主要.cpp
#include "stdafx.h"
#include "List.h"
#include <iostream>
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;
}
问题是 List.cpp 文件中“注释行”处的值 调试器显示,即使在赋值之后,该值还是空的,并且 节点实际上什么都不指向。然后下一行的头部设置为 新节点然后基本上指向不同的内存地址而不链接到前一个节点。
这是为什么?我错过了什么?
这是调试器快照:如前所述,在跨过断点后 next 指向空。根据代码,断点处的语句必须将下一个指针分配给前一个头/节点。
https://www.dropbox.com/s/yaybpukacx53fq1/Screenshot%202015-03-08%2011.33.08.png?dl=0
最佳答案
这根本不是共享指针问题。根据您的使用情况,我认为 Next
应该返回一个 reference 到 next
,但您返回的是拷贝。
(如果 Next
应该 返回一个拷贝,那么您根本不能使用 Next
来修改 下一步
,所以你必须用另一种方式来做)
关于c++ - 指向正确对象但未分配的 Shared_Ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28925939/