I don't understand what happens with the following code using functors and std::function.
My explanations are interlaced with the code (the concatenated code is compilable).
#include <chrono>
#include <functional>
class O
{
public:
void func();
};
Class O has a func-method to do something.
class FunctorClass
{
O &o_;
FunctorClass(O &o)
: o_(o) {}
std::chrono::milliseconds operator()()
{
o_.func();
return std::chrono::seconds(1);
}
};
Class FunctorClass takes a reference of an object of O and declares a operator() which returns an interval and calls func of member o_.
class TaskLoop
{
std::function<std::chrono::milliseconds(void)> task_;
public:
TaskLoop(std::function<std::chrono::milliseconds(void)> t)
: task_(t)
{}
};
TaskLoop is starting a thread and calls the task_ and sleep for the time-interval returned by this call. (Thread handling is left out here for clarity if any)
int main(void)
{
O o;
TaskLoop loop(FunctorClass(o));
getchar(); // just to have the process waiting
return 0;
}
In the main function I create an object of O. When creating the loop-object I thought I created a FunctorClass-object which itself it taken o as argument.
But this is not happening. The constructor of FunctorClass is private.
This code compiles with two different versions of GCC (4.8 and 6.x) without a related warning.
What happens? The compiler is optimizing out things, but why?
Sorry for the lengthy code, this is already a reduced test-case.
PS: When doing it with a new/shared_ptr I get the necessary compiler-warnings and errors:
std::shared_ptr<TaskLoop> t = std::make_shared<>(FunctorClass(o));