我使用的模式是这样的,C++11:
class FooViewController {
void build() {
auto label = ...
network->doWork([] (const Result& r) {
label->setText(r.text);
});
}
}FooViewController可能在doWork完成之前解构,从而导致崩溃。查看boost::signals2 2,我正在考虑使用boost::signals2::trackable,它对我的单线程目的非常有用,它的好处是我不需要直接保存和管理我的连接,但是我不知道如何使用lambda来获得这样的解决方案。
这里是一个工作的lambda免费版本:
class Foo : public boost::signals2::trackable {
public:
void bar() {
printf("Fire!");
}
};
Usage:
boost::signals2::signal<void()> signal;
{
Foo test;
signal.connect(boost::bind(&Foo::bar, &test));
signal();
}
signal();
Output:
Fired!
// Note a second 'Fired!' did not occur, which is correct behavior两个目标:
我想做这样的事情:
signal.connect(boost::bind([] {
printf("Fired!");
}, &test));在test被拆除后不会调用lambda。
2--我不想直接管理.connect返回的连接对象。
发布于 2015-08-18 01:14:11
找到引用test.cpp的答案
struct short_lived : public boost::signals2::trackable {
~short_lived() {
cout << "I'm dying...!" << std::endl;
}
};
void main() {
typedef boost::signals2::signal<void()> sig_type;
sig_type s1;
short_lived* shorty = new short_lived();
s1.connect(boost::bind<void>([](const short_lived*) {
cout << "Fire!" << std::endl;
}, shorty));
s1();
delete shorty;
s1();
}输出
Fire!
I'm dying...!...and多个params示例(boost::bind刷新器):
typedef boost::signals2::signal<void(int)> sig_type;
// ...same...
s1.connect(boost::bind<void>([](const short_lived*, int cannon) {
cout << "Fire " << cannon << "!" << std::endl;
}, shorty, _1));
s(1);
delete shorty;
s(2);输出
Fire 1!
I'm dying...!发布于 2015-11-18 22:18:29
可以看到这里:“不建议在新代码中使用可跟踪类”
也许选择使用scoped_connection或track代替。
示例:
#include <iostream>
#include <memory>
#include <boost/signals2.hpp>
struct short_lived : public boost::signals2::scoped_connection {
public:
short_lived(const boost::signals2::connection &conn) : boost::signals2::scoped_connection{conn}
{ }
~short_lived() {
std::cout << "I'm dying...1!" << std::endl;
}
};
int main() {
typedef boost::signals2::signal<void()> sig_type;
sig_type s1;
{
/* boost::signals2::scoped_connection */ short_lived conn{s1.connect([]() {
std::cout << "Fire1!" << std::endl;
})};
s1();
}
s1();
std::cout << std::endl;
{
auto lam = []() {
std::cout << "Fire2!" << std::endl;
};
/* shared_ptr with custom deleter that does not delete (since we didn't use new),
but prints a message */
std::shared_ptr<decltype(lam)> sptr{&lam, [](decltype(lam) *) { std::cout << "I'm dying...2!" << std::endl; }};
s1.connect(sig_type::slot_type(lam).track_foreign(sptr));
s1();
}
s1();
return 0;
}http://melpon.org/wandbox/permlink/c8LHGIp8ArkKsnWA
https://stackoverflow.com/questions/32060512
复制相似问题