c++ - 链表从原始指针创建 shared_ptr
问题描述
我正在尝试将我的链接列表从头部复制到 ashared_ptr
作为我remove
方法的一部分。由于某种原因,从原始指针初始化 myshared_ptr
完全删除了我的链表并用11619904替换了头值(这是我在内存中损坏的地址吗?有趣的是,您在我的调用中std::cout << "shared data " << current->data() << "\n";
看到remove
了发生了什么数据,head 正确打印为包含 0。
下面用我的编译命令和 Main 和 LinkedList 对象的源代码详细说明了这个错误:
> g++ -std=c++17 main.cpp && ./a.out
Smart ptr
0 -> 1 -> 2 -> 3 -> 4 -> nullptr
shared data 0
11619904 -> nullptr
主要的
int main() {
std::cout << "\nSmart ptr\n";
LinkedListSmart linked_list_smart(0);
for(int i=1; i<5; ++i) {
linked_list_smart.append(i);
}
std::cout << linked_list_smart << '\n';
linked_list_smart.remove(4);
std::cout << linked_list_smart << '\n';
}
链表
class LinkedListSmart
{
private:
class Node
{
private:
int m_data;
std::unique_ptr<Node> m_next;
public:
Node(int data) : m_data(data), m_next(nullptr) {}
int data() const { return m_data; }
Node* get_next() const {
Node* next = m_next.get();
return next;
}
void set_next(int data) {
m_next = std::make_unique<Node>(data);
}
Node* release_next() {
return m_next.release();
}
void reset_next(Node* next) {
m_next.reset(next);
}
};
std::unique_ptr<Node> m_head;
public:
LinkedListSmart(int data) {
m_head = std::make_unique<Node>(data);
}
Node* head() const {
return m_head.get();
}
void append(int data) {
if (m_head == nullptr) {
m_head = std::make_unique<Node>(data);
}
Node* node = head();
while(node->get_next()) {
node = node->get_next();
}
node->set_next(data);
node = nullptr; // without this will get Segmentation fault (core dumped)
delete node;
}
void remove(int data) {
if (m_head == nullptr) { return; }
Node* n = new Node(0);
n = head();
std::shared_ptr<Node> current(n);
std::shared_ptr<Node> previous = nullptr;
std::cout << "shared data " << current->data() << "\n";
}
friend std::ostream& operator<<(std::ostream& os, const LinkedListSmart& linked_list_smart) {
auto node = linked_list_smart.head();
if(node == nullptr) {
os << "List is empty\n";
}
else {
while(node) {
os << node->data() << " -> ";
node = node->get_next();
}
}
os << "nullptr";
delete node;
return os;
}
};
解决方案
目前std::cout << "shared data " << current->data() << "\n";
current
并m_head
拥有相同的原始指针,并且两者都是有效的。但在remove()
current
破坏和删除原始指针的末尾。现在m_head
包含悬空指针。linked_list_smart
销毁时m_head
删除(已删除)指针。你也有内存泄漏:
Node* n = new Node(0);
n = head();
正如@QuestionC 指出的那样,不要删除 . 拥有的原始指针unique_ptr
。
推荐阅读
- selenium - 为什么 Selenium 有时无法找到没有错误的 href
- go - 如何从现有数据库(无模型)中使用 gorm 查找表之间的关系/关联?
- file - Ariba 引导 Buyinf j.son 文件上传错误消息:!资源“MeetingEvents_NEW”创建失败:没有第 5 组;;
- java - 如何运行位于不属于 cmd 包的子文件夹的 .class 文件?
- visual-c++ - 为什么 VS 为我的析构函数标记 C26432?
- hosting - Streamlit 托管
- python - Python中的清除屏幕方法无法正常工作
- c# - 使用 Json.NET,如何将两个需要序列化的 C# 对象合并在一起?
- javascript - 进程完成后阻止 node.js 应用程序退出
- c# - 希望我的 while 循环在我输入一个超过 800 的数字后完成并输出,但它给了我未处理的异常