#include <iostream>
void foo(int k) {
static auto bar = [&]{
std::cout << k << std::endl;
};
bar();
}
int main () {
foo(1); foo(2); foo(3); // output is correct: 1, 2, 3
}
関数foo、静的ラムダが参照によってkをキャプチャする方法を確認してください。これは機能しているようで、 intではなくより複雑なデータ型でも同じことが起こっています。
これは期待されていますか?kのアドレスがfooの呼び出しごとに同じになるという保証はありますか、それともUBですか?
事前に感謝します。これが以前に回答されていた場合は申し訳ありません(成功せずに同様の質問を見つけようとしました)