我std::shared_ptr在c ++中发现了一个非常奇怪的行为.以下示例与标准指针完美配合.
然而,std::shared_ptr这里的使用原因是分段错误.(见下面的回溯)
我知道,std::shared_ptr从多个线程访问是不安全的,因此我正在使用原子操作.即使是经典的锁也无法解决问题.
IM使用gcc version 6.3.0 20170406 (Ubuntu 6.3.0-12ubuntu2)与-Wall -O2 -g和 -std=c++17
有人知道解决方案或代码崩溃的原因吗?
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
template <typename T>
class list {
private:
struct Node {
T value;
std::shared_ptr<Node> next;
Node() : next(nullptr) {}
};
std::shared_ptr<Node> head;
public:
// create dummy-nodes
explicit list() : head(std::make_shared<Node>()){
head->next = std::make_shared<Node>();
};
void push_front(T val) {
std::shared_ptr<Node> current;
std::shared_ptr<Node> next;
std::shared_ptr<Node> newNode = std::make_shared<Node>();
newNode->value = val; …Run Code Online (Sandbox Code Playgroud)