av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

C++代碼賞析:回調(diào)中對(duì)象保活

概念

  • 類模板 std::function 是通用多態(tài)函數(shù)包裝器。 std::function 的實(shí)例能存儲(chǔ)、復(fù)制及調(diào)用任何可復(fù)制構(gòu)造(CopyConstructible)可調(diào)用(Callable)目標(biāo)——函數(shù)、 lambda 表達(dá)式、 bind 表達(dá)式或其他函數(shù)對(duì)象,還有指向成員函數(shù)指針和指向數(shù)據(jù)成員指針。
  • std::enable_shared_from_this 能讓其一個(gè)對(duì)象(假設(shè)其名為 t ,且已被一個(gè) std::shared_ptr 對(duì)象 pt 管理)安全地生成其他額外的 std::shared_ptr 實(shí)例(假設(shè)名為 pt1, pt2, ... ) ,它們與 pt 共享對(duì)象 t 的所有權(quán)。

例子1

您可能希望將this指針捕獲到c++ lambda中,但這將捕獲原始指針。如果需要延長(zhǎng)對(duì)象的生命周期,則需要捕獲強(qiáng)引用。“捕獲對(duì)自己的強(qiáng)引用”的常見(jiàn)模式是同時(shí)捕獲強(qiáng)引用和原始this。強(qiáng)引用保持this為活的,并且使用this方便訪問(wèn)成員。

#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

在線測(cè)試

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

網(wǎng)頁(yè)題目:C++代碼賞析:回調(diào)中對(duì)象保活
網(wǎng)址分享:http://uogjgqi.cn/article/dpjdcgo.html
掃二維碼與項(xiàng)目經(jīng)理溝通

我們?cè)谖⑿派?4小時(shí)期待你的聲音

解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流