However, I'm afraid I don't understand something - the way functions are supposed to be passed around in VC2010.
I want to thank Washu for his article on functional programming. From there, I get the idea that functors work just like everything else. They can be passed by reference such as in [font=courier new,courier,monospace]MulticastEvent::AddHandler[/font] or by value, by storing in [font=courier new,courier,monospace]std::vector<EventSignature>[/font].
Great, but I'm having some difficulty in understanding a behavior here.
Consider:
#include <iostream>
#include <functional>
using namespace std;
typedef function<void()> PrintFunc;
void Nothing(const PrintFunc &blah) {
blah();
}
void Nothing_value(const PrintFunc blah) {
blah();
}
struct Callbacks {
PrintFunc const& func; // (2)
Callbacks(PrintFunc const& call) : func(call) { }
};
int main() {
auto lines = []() { cout<<"- - - - - -"<<endl; };
auto dots = []() { cout<<". . . . . ."<<endl; };
Nothing(lines);
Nothing_value(dots);
{
Callbacks one(lines); // (1)
one.func();
}
{
Callbacks two(dots);
two.func();
}
return 0;
}
Everything seems to be fine up to line (1). Here, I suppose I have a complex function taking lots of callbacks I want to encapsulate in a single struct, similarly to how C# dispatches events via delegates as far as I've understood.
The result of this code is that the reference contained in the struct won't be initialized correctly. It is not initialized even immediately after creation. The situation shows in the debugger as attached.
However, if I change line (2) to value type, everything works as expected.
Is this a quirk in the compiler or am I missing something?