在c 11 lambdas
{std :: cout 此代碼使用[&]語法通過引用捕獲變量x。問題出現了該程序是否保證在不調用未定義的行為的情況下輸出5。 答案:是
,代碼可確保正常工作。在檢查基礎標準措辭之前,必須注意,該代碼的功能按C委員會的意圖運行。但是,在此問題上尚不清楚C 11標準的最初措辭,導致2011年CWG發行以提供澄清。 This issue is being addressed in the ongoing development of the C standard.#include
#include
std::function make_function(int& x) {
return [&]{ std::cout According to [expr.prim.lambda]/17 of the C standard, only id-expressions referring to entities captured by copy are transformed into a member access on the lambda closure type.指代通過參考捕獲的實體的ID表達是單獨的,並繼續表示它們在封閉範圍中表示的相同實體。
在上面的代碼中,被捕獲的實體是make_function函數的參數x,它屬於lambda的到達範圍內。因此,lambda表達式中的參考x是指主函數中聲明的原始變量。 最初可能會出現問題,因為在make_function函數返回後,在其壽命之外被引用x。但是,在有限的情況下,可以在其壽命之外引用參考文獻。通常,引用要么在範圍內聲明,要么是類成員,在這種情況下,類本身必須在其壽命內。 因此,標準不會明確禁止在其壽命外使用參考文獻。 This loophole allowed for the capturing of references by reference in lambda expressions to be supported.
CWG Issue 2012 and Future Clarification
CWG issue 2012 was raised to address the oversight that references could be referenced outside their lifetime under certain circumstances.該問題的解決方法無意間通過參考引用來影響lambda捕獲的規範。但是,預計該回歸將在發布C 17之前修復。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3