lundi 9 mars 2020

C++11 function object cannot invoke a target, which is another function object

I have encountered a program like this:

#include <iostream>
#include <functional>
#include <string>

std::function<void ()> foo(){
    const auto s = std::string("bar");
    return [&]{std::cout << s << '\n';};
}

int main()
{
    const auto fun = foo();
    fun();

    return 0;
}

I am struggling to understand what is wrong with this program and how to fix it.

My understanding is that fun should be able to invoke its target foo and print out bar but instead there is no output.

I appreciate any helps!

Aucun commentaire:

Enregistrer un commentaire