8
#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ですか?

事前に感謝します。これが以前に回答されていた場合は申し訳ありません(成功せずに同様の質問を見つけようとしました)

4

2 に答える 2

1

The reason it's probably "working" in your example is that the call stack is always lining up the same way. Try this instead and see if you still get the "expected" output.

#include <iostream>

void foo(int k) {
    static auto bar = [&]{
        std::cout << k << std::endl;
    };
    bar();
}

void baz(int k) {
    std::cout << "baz: ";
    foo(k);
}

int main () {
    foo(1); baz(2); foo(3);
}
于 2013-04-17T22:24:06.063 に答える