美图齐众专注资阳网站设计 资阳网站制作 资阳网站建设
资阳网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

C++代码赏析:回调中对象保活

概念

  • 类模板 std::function 是通用多态函数包装器。 std::function 的实例能存储、复制及调用任何可复制构造(CopyConstructible)可调用(Callable)目标——函数、 lambda 表达式、 bind 表达式或其他函数对象,还有指向成员函数指针和指向数据成员指针。
  • std::enable_shared_from_this 能让其一个对象(假设其名为 t ,且已被一个 std::shared_ptr 对象 pt 管理)安全地生成其他额外的 std::shared_ptr 实例(假设名为 pt1, pt2, ... ) ,它们与 pt 共享对象 t 的所有权。

例子1

您可能希望将this指针捕获到c++ lambda中,但这将捕获原始指针。如果需要延长对象的生命周期,则需要捕获强引用。“捕获对自己的强引用”的常见模式是同时捕获强引用和原始this。强引用保持this为活的,并且使用this方便访问成员。

#include 
#include
#include
#include

std::vector> actions;

class Widget : public std::enable_shared_from_this {
public:
Widget(const std::string name){name_ = name;}
void reg(){
// std::shared_ptr
auto callback = [lifetime = shared_from_this(), this]() {
action(name_);
};
actions.push_back(callback);
}

virtual void action(std::string name){
std::cout << "widget action:" << name << std::endl;
}
std::string name_;
};
class Table : public Widget {
public:
Table(const std::string name):Widget(name){}
virtual void action(std::string name){
std::cout << "table action:" << name << std::endl;
}
};

void reg_action(){
auto widget = std::make_shared("widget");
widget->reg();
auto table = std::make_shared("table");
table->reg();
}

int main(int argc, char* argv[]){
reg_action();
for (const auto& action : actions) {
action();
}
}

输出:

widget action:widget
table action:table

在线测试

https://wandbox.org/permlink/HDrKO6Hn6tROiVEj

例子2

#include 
#include
#include

std::vector> actions;

class Widget : public std::enable_shared_from_this {
public:
void reg(){
actions.push_back(std::bind(&Widget::action, shared_from_this()));
}

virtual void action(){
std::cout << "widget action" << std::endl;
}
};

class Table : public Widget {
public:
virtual void action(){
std::cout << "table action" << std::endl;
}
};

void reg_action(){
auto widget = std::make_shared();
widget->reg();
auto table = std::make_shared
();
table->reg();
}

int main(int argc, char* argv[]){
reg_action();
for (const auto& action : actions) {
action();
}
}

输出:

widget action
table action

本文题目:C++代码赏析:回调中对象保活
标题来源:http://www.zsjierui.cn/article/dpjdcgo.html

免费获取网站建设与品牌策划方案报价

*主要业务范围包括:高端网站建设, 集团网站建设(网站建设网站制作)找网站建设公司就上美图齐众。
提交需求

    联系我们

    028-86922220
  • 手机:13518219792
  • 地址:成都市太升南路288号锦天国际A幢1002号
  • 24小时服务热线:028-86922220

    网站建设服务

  • 网页设计
  • 网站制作
  • 网站开发

    网站推广服务

  • 营销网站建设
  • 百度快速排名
  • 整站网站推广

    网站运维服务

  • 基础维护
  • 网站改版
  • 网站维护

    FOLLOW US

  • 微信二维码

    微信二维码

Copyright © 2025 资阳站青羊区美图齐众设计工作室(个体工商户) 资阳网站建设公司-选网站建设公司美图齐众!专业的网站制作公司!
All Rights Reserved 版权所有 蜀ICP备2025119604号-1