[英]Passing Functor with state as parameter in c++
我正在嘗試使用Functor對象實現一個簡單的回調。 我有一個帶有print(string)
函數的Caller類,它調用傳遞輸入字符串的回調。 在回調中,我正在收集所有字符串,稍后在printEverything
方法中打印它。 但即使回調正在發生(由輸出驗證),但printEverything
方法中沒有任何內容打印。
class Callback {
public:
Callback() {
cout << "constructing Callback..." << std::endl;
}
void operator()(std::string data) {
cout << "Adding record in callback: " << data << std::endl;
records.push_back(data);
}
void printEverything() {
cout << "Printing everything: " << std::endl;
for(auto a : records) {
cout << a;
}
}
private:
std::vector<string> records;
};
class Caller {
public:
template <typename Func>
Caller(Func&& func) : cb_ (func){
}
void print(std::string str) {
cb_(str);
cout << "Printing in caller: " << str << std::endl;
}
private:
std::function<void(std::string)> cb_;
};
int main(int argc, char **argv) {
Callback callback;
Caller caller(callback);
caller.print("Hello");
caller.print("World");
callback.printEverything(); // This doesn't print any records
}
輸出:
constructing Callback...
Adding record in callback: Hello
Printing in caller: Hello
Adding record in callback: World
Printing in caller: World
Printing everything:
看起來,回調發生在與我在主范圍內不同的對象上。 任何想法在這里出了什么問題?
std::function
拷貝(或移動到它時移動)你傳遞給它的函數(參見它的構造函數 )。 因此,這個回調發生不同的對象比callback
。
如果要傳遞對函數的引用,請使用std::ref
- 它有一個operator()
:
int main() {
Callback callback;
// Be careful with lifetime management. `caller` must not outlast `callback`
Caller caller(std::ref(callback));
caller.print("Hello");
caller.print("World");
callback.printEverything();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.