c++ - 在弱指针上调用函数
问题描述
我写了以下代码:
#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);
适用于共享指针,但同样不适用于弱指针。
解决方案
您不能对weak_ptr 进行操作。如果 shared_ptr 已被删除,就像取消引用已删除的原始指针一样。
每当您想访问其中包含的指针时,您都会锁定它以验证您的 shared_ptr 是否仍然存在。
if (auto sp = wp.lock()) {
sp->set(10);
} else {
// sp no longer exists!
}
推荐阅读
- php - 如何将 PHP 变量封装在字符串中?(在 POST 请求正文中)
- node.js - 间距大于0的Mapbox gl原生拼接图块
- c++ - 用正整数填充数组
- jsf - 如何使用 PrimeFaces Diagram 导出图像文件
- rest - 无法通过 JAVA REST API 连接到雪花
- c++ - C++:从文件中读取 xy 数据会创建无限循环?
- git - 如何构建符合 GDPR 的基于 git 的静态页面?
- c - typedef 的用途是什么,它的正确用途是什么?
- json - 将 JSON 转换为 CSV1,然后将输出与另一个 CSV2、vb.net 进行比较
- imagemagick - 如何将 dzi 文件转换为多瓦锥体 tiff 格式