Search code examples
c++function-pointers

pointers to member functions with move semantics


When you have a pointer to a non-static member function of an object on the stack, what exactly happens when the object changes its location because of an move? Does the pointer still point to the location of the moved-from object and thus is invalid/dangling?


Solution

  • Pointers to member functions do not hold a reference to any instance of the class. This is true even for pointers to non-static member functions.

    Such a pointer can be constructed without having an instance of the class:

    class star {
    public:
        void shine();
    };
    
    void (star::* smile)() = &sun::shine;
    

    And an instance needs to be specified when calling it:

    star sun;
    
    (sun.*smile)();
    std::memfn(smile)(sun);