13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

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

概念

例子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++代码赏析:回调中对象保活
URL链接:http://cdbrznjsb.com/article/dpjdcgo.html
  • 网站建设专属方案

  • 网站定制化设计

  • 7X24小时服务

  • N对管家服务

让你的专属顾问为你服务