我想创建一个我想要超出范围的对象,但是设置对其字段的引用。这种做法有什么好处吗?
A* a;
B* b;
[a, b]
{
static Loader loader("some", "argument", "the constructor", "takes");
a = loader.getA();
b = loader.getB();
}();
匿名lambda是否以其拥有的值被破坏?是否有更好的设计模式来实现同样的目标?
好吧,这似乎是一个很好的方法。我的问题仍然是,如果匿名lambda在解析时被破坏(并且使用它拥有的静态变量)。
答案 0 :(得分:6)
你不需要lambda来做这件事。 static
变量可以在块范围内声明,因此您可以重构为
A* a;
B* b;
{
static Loader loader("some", "argument", "the constructor", "takes");
a = loader.getA();
b = loader.getB();
}
// more code
现在loader
永远不能再次直接访问(它超出范围)但你可以存储指针/引用它或它的成员(它的生命持续到程序结束)。
另外,为了回答关于临时lambda的生命周期的问题,如果你没有捕获它们,它们就会被销毁。
[](){ /* some code */ }();
将创建一个对象,调用它的operator()
,然后销毁该临时对象。