When should I make explicit use of the `this` pointer?

后端 未结 12 1287
甜味超标
甜味超标 2020-11-22 15:19

When should I explicitly write this->member in a method of a class?

12条回答
  •  野性不改
    2020-11-22 16:00

    The other uses for this (as I thought when I read the summary and half the question... .), disregarding (bad) naming disambiguation in other answers, are if you want to cast the current object, bind it in a function object or use it with a pointer-to-member.

    Casts

    void Foo::bar() {
        misc_nonconst_stuff();
        const Foo* const_this = this;
        const_this->bar(); // calls const version
    
        dynamic_cast(this)->bar(); // calls specific virtual function in case of multi-inheritance
    } 
    
    void Foo::bar() const {}
    

    Binding

    void Foo::baz() {
         for_each(m_stuff.begin(), m_stuff.end(),  bind(&Foo:framboozle, this, _1));        
         for_each(m_stuff.begin(), m_stuff.end(), [this](StuffUnit& s) { framboozle(s); });         
    } 
    
    void Foo::framboozle(StuffUnit& su) {}
    
    std::vector m_stuff;
    

    ptr-to-member

    void Foo::boz() {
        bez(&Foo::bar);
        bez(&Foo::baz);
    } 
    
    void Foo::bez(void (Foo::*func_ptr)()) {
        for (int i=0; i<3; ++i) {
            (this->*func_ptr)();
        }
    }
    

    Hope it helps to show other uses of this than just this->member.

提交回复
热议问题