小编Dom*_*mso的帖子

奇怪的shared_ptr行为

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)

c++ atomic lock-free shared-ptr c++11

4
推荐指数
1
解决办法
1153
查看次数

标签 统计

atomic ×1

c++ ×1

c++11 ×1

lock-free ×1

shared-ptr ×1