c++lambdaconstructorc++14this-pointer

Is it legal to refer to this pointer and hook up a lambda from inside the constructor of a class?


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.


Solution

  • This is fine. The object of the class MyClass exists at this point. So the pointer this is valid, and of course the class someClass has been completely constructed as well.

    The only thing to watch out for is the order of member initialisation of MyClass - but only really in the initialiser list, although since you are not using an initialiser list here it is not an issue in this example anyway...