首页 > 解决方案 > 在弱指针上调用函数

问题描述

我写了以下代码:

#include <iostream>
#include <memory>
using namespace std;

class Foo
{
    int x = 0;
public:
    int get() const { return x; }
    void set(int x) { this->x = x; }
};

int main(){
    auto sp = shared_ptr<Foo>(new Foo());    
    weak_ptr<Foo> wp;
    wp = sp;
    return 0;
}

我想调用在共享指针sp和 on 上设置wp的方法,调用它的正确方法是什么?我发现这sp->set(5);适用于共享指针,但同样不适用于弱指针。

标签: c++weak-ptr

解决方案


您不能对weak_ptr 进行操作。如果 shared_ptr 已被删除,就像取消引用已删除的原始指针一样。

每当您想访问其中包含的指针时,您都会锁定它以验证您的 shared_ptr 是否仍然存在。

if (auto sp = wp.lock()) {
  sp->set(10);
} else {
  // sp no longer exists!
}

推荐阅读