【发布时间】:2015-06-08 13:56:17
【问题描述】:
我有时在我的课堂上有这种模式:
class Variant;
struct Foo
{
int x;
int y;
};
struct Bar
{
int first() const;
int second() const;
};
class Bar
{
public:
Bar(Variant v)
{
// For brevity there are no
// tests in this sample code
Bar aBar = v.get<Bar>(); // Variant::get is a slow operation
m_theFoo.x = aBar.first();
m_theFoo.x = aBar.second();
}
private:
Foo m_theFoo;
};
我宁愿在初始化列表中初始化 m_theFoo。但是,我不想像这样两次调用Variant::get,因为这可能是一个缓慢的操作:
Bar(Variant v):
m_theFoo{v.get<Bar>().first(), v.get<Bar>().second()}
{
}
所以我想出了这个:
Bar(Variant v):
m_theFoo{[&] () {
Bar aBar = v.get<Bar>();
return Foo{aBar.first(), aBar.second()};
}()
}
{
}
基本上,初始化是由调用并返回初始化成员的 lambda 完成的。
我想知道这听起来是好还是坏,以及这种初始化方法是否有缺点。例如,lambda 实例化的重量是多少?
把它变成这样的无状态 lambda 会更好吗?
Bar(Variant v):
m_theFoo{[] (const Variant& v_sub) {
Bar aBar = v_sub.get<Bar>();
return Foo{aBar.first(), aBar.second()};
}(v)
}
{
}
【问题讨论】:
标签: c++ lambda initialization