为什么在使用sharedptr时会出现运行时异常

why am i getting this runtime exception when using shared_ptr?

本文关键字:运行时 异常 sharedptr 为什么      更新时间:2023-10-16

在下面的代码中,我在返回1后得到以下运行时异常(可能是内存泄漏);和在Node()的析构函数中。

Unhandled exception at 0x0f9bad4a (msvcp100d.dll) in test.exe: 0xC0000005: Access violation reading location 0xfeeefef2.

我已经有一段时间没有使用smart_ptr了,所以我想知道我在这里做错了什么?

#include <vector>
#include <queue>
#include <memory>
#include <iostream>
using namespace std;
class Node;
typedef shared_ptr<Node> SharedNode;
class Node {
    Node* parent;
    vector< SharedNode > children;
    int value;
    //limiting construction
    Node(int a_value):value(a_value),parent(0){}
    Node(const Node &copy); //non-construction-copyable
    Node& operator=(const Node& copy); //non-copyable
public:
    static SharedNode create(int a_value){
        return SharedNode(new Node(a_value));
    }
    SharedNode addChild(SharedNode child){
        child->parent = this;
        children.push_back(child);
        return child;
    }
SharedNode getNode(int searchValue);
};
SharedNode Node::getNode(int searchValue){
    // Breadth First Search
    queue<SharedNode> que;
    que.push(SharedNode(this));
    while(!que.empty()){
        SharedNode node = que.front();
        que.pop();
        if(node->value == searchValue)
            return node;
        vector<SharedNode>::iterator it;
        for(it = node->children.begin(); it != node->children.end(); it++){
            que.push(*it);
        }
    }
    return 0;
}
int main(){
    SharedNode node_ptr = Node::create(5);
    for(int i  = 0; i < 4; ++i)
        node_ptr->addChild(Node::create(i));
    cout << (node_ptr->getNode(-1) != 0 ? "Found" : "Not found");
    return 1;
}

当我在这个问题上使用shared_ptr时,我觉得我搞砸了,比如:shared_ptr(this)。但是,那是我的猜测。

我在这里做错了什么?

问题来自

que.push(SharedNode(this));

这将创建一个新的共享指针,该指针现在拥有this。但是,由于create()方法,存在另一个拥有相同对象的共享指针。这可能导致双重删除。

如果您有理由在这种情况下使用共享指针,那么正确的解决方案是enable_shared_from_this

首先,将节点定义更改为此。

class Node : public std::enable_shared_from_this<Node> { ...

然后将违规行更改为

que.push(this->shared_from_this());

这导致它返回一个指向对象的shared_ptr,但它与已经存在的shared_pt共享,而不是两个单独的shared_pter对象。

注意,为了使this->shared_from_this()的使用合法,对象必须由shared_ptr所有。您已经通过静态create()方法实现了这一点,但我想确保您理解其局限性。

编辑:shared_ptr所有权的简要说明。

当您使用构造函数从原始指针创建shared_ptr时,它会创建一个引用对象,该对象包含指向该对象的指针和引用计数,用于确定有多少shared_ptr对象指向它。然后,指向该引用对象的指针会传递给从该原始shared_ptr生成的所有副本,其中引用计数跟踪有多少CCD_ 15对象引用它

当您调用shared_ptr(this)时,共享指针无法知道this由另一个共享指针拥有,并创建一个新的引用对象。一旦其中一个引用计数为零,该对象将被删除,尽管另一个shared_ptr引用对象仍指向它,从而导致一个悬空指针和您看到的错误。

如果您只需要在父节点存在时存在子节点,我会考虑将Node更改为只具有其他节点的std::vector(移除指针)。当最高级别的节点通过其析构函数被销毁时,它将销毁向量,从而销毁子节点,依此类推。

class Node
{
  // whatever operations you need... 
  std::vector<Node> children;
}

编辑:根据要求。。。

如果你有一个用例,你真的想让孩子比父母活得更长,你就必须处理父指针,因为它可能会在孩子之前被销毁。一个快速的解决方案是确定你是否真的需要父指针,如果你不需要,就去掉它

但是,假设您仍然希望保留它,则不能在此处使用shared_ptr。如果你这样做,你会有一个循环依赖,两者都不会被自动销毁,这不是你想要的。

这里的解决方案是使用std::weak_ptr。基本上,它与shared_ptr引用对象的交互方式不会阻止指向对象的破坏。

class Node
{
private:
   std::weak_ptr<Node> parent;
   // Other constructors.  
   Node(int a_value):value(a_value),parent() {} 
public:
   SharedNode addChild(SharedNode child){
        child->parent = this->shared_from_this(); // Initialize their pointer using
                                                  // your shared pointer
        children.push_back(child);
        return child;
   }
   // This function will return a shared_ptr to nullptr (and will evaluate false) 
   // if you have no parent, or if the parent node has been deleted
   SharedNode getParent()
   {
       return parent.lock();
   }
};

考虑以下代码会发生什么:

Node * dumb_ptr = new Node;
shared_ptr<Node> smart1 = dumb_ptr;
shared_ptr<Node> smart2 = dumb_ptr;

你现在有两个聪明的指针,它们都认为自己拥有同一个对象。其中一个将删除对象,另一个将在某个时刻尝试使用或删除已删除的对象。解决此问题的方法是始终从另一个智能指针或new创建智能指针。最好不要使用任何愚蠢的指针,包括this

shared_ptr<Node> smart1 = new Node;
shared_ptr<Node> smart2 = smart1;