enable_shared_from_this

本文介绍C++中std::enable_shared_from_this类模板,它允许被std::shared_ptr管理的对象安全地创建额外的共享所有权实例。文章通过示例对比了正确与错误的用法,并解释了内部实现机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::enable_shared_from_this

 
C++
 
 
 
std::enable_shared_from_this
 
Defined in header <memory>
  
template<class T > class enable_shared_from_this;
 (since C++11)
   

std::enable_shared_from_this allows an object t that is currently managed by astd::shared_ptr namedpt to safely generate additional std::shared_ptr instancespt1, pt2, ... that all share ownership of t with pt.

Inheriting from std::enable_shared_from_this<T> provides the typeT with a member function shared_from_this. If an objectt of type T is managed by a std::shared_ptr<T> named pt, then calling T::shared_from_this will return a newstd::shared_ptr<T> that shares ownership of t with pt.

Note that prior to calling shared_from_this on an object t, there must be astd::shared_ptr that ownst.

Also note that enable_shared_from_this provides an alternative to an expression likestd::shared_ptr<T>(this), which is likely to result in this being destructed more than once by multiple owners that are unaware of each other.

Member functions

constructs an enabled_shared_from_this object
(protected member function)
destroys an enable_shared_from_this object
(protected member function)
returns a reference to this
(protected member function)
returns a shared_ptr which shares ownership of*this
(public member function)

Notes

A common implementation for enable_shared_from_this is to hold a weak reference (such asstd::weak_ptr) tothis. The constructors ofstd::shared_ptr detect the presence of anenable_shared_from_this base and assign the newly created std::shared_ptr to the internally stored weak reference. Constructing astd::shared_ptr for an object that is already managed by anotherstd::shared_ptr will not consult the internally stored weak reference and thus will lead to undefined behavior.

Example

#include <memory>
#include <iostream>
 
struct Good: std::enable_shared_from_this<Good>
{
    std::shared_ptr<Good> getptr() {
        return shared_from_this();
    }
};
 
struct Bad
{
    std::shared_ptr<Bad> getptr() {
        return std::shared_ptr<Bad>(this);
    }
    ~Bad() { std::cout << "Bad::~Bad() called\n"; }
};
 
int main()
{
    // Good: the two shared_ptr's share the same object
    std::shared_ptr<Good> gp1(new Good);
    std::shared_ptr<Good> gp2 = gp1->getptr();
    std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';
 
    // Bad, each shared_ptr thinks it's the only owner of the object
    std::shared_ptr<Bad> bp1(new Bad);
    std::shared_ptr<Bad> bp2 = bp1->getptr();
    std::cout << "bp2.use_count() = " << bp2.use_count() << '\n';
} // UB: double-delete of Bad



Output:

gp2.use_count() = 2
bp2.use_count() = 1
Bad::~Bad() called
Bad::~Bad() called
*** glibc detected *** ./test: double free or corruption

See also

### 如何使用 Dify 创建 ChatFlow Dify 是一款强大的工具,支持 RAG 和 Chat 功能,并允许用户通过简单的配置来创建复杂的对话流 (ChatFlow)[^1]。以下是关于如何利用 Dify 来构建 ChatFlow 的详细说明。 #### 配置环境 在开始之前,确保已经安装并运行了 Dify 平台。如果尚未完成此操作,请参考官方文档或相关教程进行初始化设置[^2]。 #### 创建基础 Chat 流程 1. **启动新项目** 登录到 Dify 控制面板后,在界面中找到新建项目的选项,选择适合自己的模板或者手动建立空白项目用于自定义开发[^1]。 2. **集成大模型服务** 在 Dify 中可以通过简单几步实现与主流云端 AI 模型以及本地化部署的大规模预训练模型连接。这一步通常涉及 API 密钥输入或其他认证方式验证过程。 3. **设计交互逻辑** 使用图形化编辑器拖拽节点组件来搭建整个会话路径图谱。每个节点代表特定功能模块比如问候语句处理、问题分类解析等环节;边线则表示不同条件分支下的跳转关系。 4. **测试初步效果** 完成上述基本架构设定之后就可以立即试用看看实际表现情况怎么样啦!点击模拟按钮开启一轮虚拟客户交流体验吧~ 如果发现某些地方不够理想的话记得返回调整优化哦! #### 进阶定制化 当熟悉了基础框架运作原理以后还可以进一步探索更多高级特性: - 添加多媒体素材支持:除了纯文字形式外还能够嵌入图片链接地址甚至是实时音视频通话能力扩展; - 调整权重算法提升精准度:通过对历史数据的学习不断改进预测准确性从而让回复更加贴近真实需求场景; - 外部数据库联动查询:假如企业内部存在现成可用的数据源那么完全可以将其无缝融入进来作为补充参考资料来源之一。 ```python # 示例代码片段展示如何调用远程API接口获取动态更新内容填充至最终呈现给用户的答案部分当中去。 import requests def fetch_latest_news(topic): url = f"https://api.example.com/news?topic={topic}" response = requests.get(url) if response.status_code == 200: news_data = response.json() return news_data['articles'][0]['title'] else: return "Failed to retrieve the latest news." latest_headline = fetch_latest_news('technology') print(latest_headline) ``` 以上就是有关于怎样借助 Dify 工具平台快速高效地打造出属于自己的个性化聊天机器人解决方案的整体思路概述。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值