我试图了解如何std::shared_ptr在C++中使用.但它很混乱,我不明白如何创建指向同一对象的多个共享指针.即使是文档和在线资料也不是很清晰.
以下是我编写的一小段代码,用于尝试和理解其std::shared_ptr行为:
#include <iostream>
#include <memory>
using namespace std;
class Node
{
public:
int key;
Node()
{
key = 0;
}
Node(int k)
{
key = k;
}
};
int main()
{
Node node = Node(10);
shared_ptr<Node> ptr1((shared_ptr<Node>)&node);
cout << "Use Count: " << ptr1.use_count() << endl;
// shared_ptr<Node> ptr2=make_shared<Node>(node);//This doesn't increase use_count
shared_ptr<Node> ptr2((shared_ptr<Node>)&node);
cout << "Use Count: " << ptr2.use_count() << endl;
if (ptr1 == ptr2)
cout << "ptr1 & ptr2 point to the …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用C++ 实现基于Lazy Concurrent List的 C++ shared_ptr.我的理由是,它unreachable nodes会被最后一个自动释放shared_ptr.根据我的理解,a上的递增和递减操作shared_ptr's reference count是原子的.这意味着只有最后一个引用该节点的shared_ptr应该为该节点调用delete/free.我为多个线程运行程序,但我的程序崩溃了错误double free called或只是分段错误(SIGSEGV).我不明白这是怎么可能的.下面给出了我的实现代码,方法名称表示它们的预期操作.
#include<thread>
#include<iostream>
#include<mutex>
#include<climits>
using namespace std;
class Thread
{
public:
std::thread t;
};
int n=50,ki=100,kd=100,kc=100;`/*no of threads, no of inserts,deletes & searches*/`
class Node
{
public:
int key;
shared_ptr<Node> next;
bool marked;
std::mutex nodeLock;
Node() {
key=0;
next = nullptr;
marked = false;
}
Node(int k) {
key …Run Code Online (Sandbox Code Playgroud) c++ multithreading shared-ptr segmentation-fault double-free