Passing “this” to a function from within a constructor?

后端 未结 4 1556
无人共我
无人共我 2021-02-05 02:19

Can I pass \"this\" to a function as a pointer, from within the class constructor, and use it to point at the object\'s members before the constructor returns?

Is it saf

4条回答
  •  渐次进展
    2021-02-05 02:58

    As a side-note on the presented code, I would instead templatize the void*:

    class Stuff
    {
    public:
        template 
        static void print_number(const T& t)
        {
            std::cout << t.number;
        }
    
        int number;
    
        Stuff(int number_)
        : number(number_)
        {
            print_number(*this);
        }
    };
    

    Then you'd get a compile error if the type of t doesn't have a number member.

提交回复
热议问题