Scenario:
I have class like below which hooks up a lambda in the constructor itself. And the lambda calls a class member function in turn.
Code:
class SomeClass {
public:
typedef std::function<void(int)> Callback;
void ListenForCallback(const Callback& callback) {
m_callback = callback;
}
private:
Callback m_callback;
}
class MyClass {
public:
MyClass() {
m_some_class = std::make_unique<SomeClass>();
// Here in constructor itself I pass this pointer and hooking up to a lambda which calls a member function. Is this legal?
m_some_class->ListenForCallback([this](int value) {
std::cout << "Value is: " << value << std::endl;
TakeAction();
})
}
private:
std::unique_ptr<SomeClass> m_some_class;
void TakeAction() {
// Please do something
}
}
Question:
I was skeptical about using the this
pointer in the MyClass
's constructor itself. And even further skeptical about hooking up a lambda calling a member. But, I found that above code works! Am I doing everything legal and correct in above code?
Is it valid to refer to this
pointer in the constructor of a class? I wish to know if its valid/invalid and the explanation or reasoning behind the answer.
Environment:
C++ 14 code compiled with Clang and GCC compilers.