日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C++代碼賞析:回調(diào)中對象保活

概念

  • 類模板 std::function 是通用多態(tài)函數(shù)包裝器。 std::function 的實例能存儲、復制及調(diào)用任何可復制構(gòu)造(CopyConstructible)可調(diào)用(Callable)目標——函數(shù)、 lambda 表達式、 bind 表達式或其他函數(shù)對象,還有指向成員函數(shù)指針和指向數(shù)據(jù)成員指針。
  • 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

網(wǎng)頁名稱:C++代碼賞析:回調(diào)中對象保活
URL分享:http://www.dlmjj.cn/article/dpjdcgo.html

<td id="epm92"></td>

<td id="epm92"></td>