c++ - is it allowed to pass *this as an argument of a function accepting a reference(&)? -


i have been using method without problem, want make sure if totally allowed approach or being lucky!

class { public:     void bar()     {         foo(*this);     } };  void foo(a &a) {  } 

thank you

as long void foo(a&) (forward) declared a::bar knows existance it's valid , 100% allowed.


notes

  • is there anywhere may not dereference this?

    not really, there few issues should know about. if want use *this in initialization list of constructing object please remember not allowed access virtual or uninitialized members of object through it; neither directly nor indirectly.

  • if member-function declared const functions taking const (reference) allowed called using dereferenced this-pointer, see below example.

void func (struct obj&); void func (struct obj const&);  struct obj {   void bar () const {     func (*this);   }    void bar () {     func (*this);   } }; 

int main (int argc, char *argv[]) {   obj       a;     obj const b;    a.bar (); /* func (obj &) */   b.bar (); /* func (obj const&) */ } 

Comments