c++ - Using t( *this ) results RuntimeError, while t( std::ref( *this ) does not -


i have following example:

#include <iostream> #include <functional>  struct tmr {     typedef std::function<void(void)> callback;     callback cb;      tmr(callback cb_) :         cb( cb_ )     {     }      void timeout()     {         cb();     } };  struct obj {     struct tmr t;      obj() :         t( std::ref( *this ) )     {     }      void operator () ()     {         std::cout << __func__ << '\n';     } };  int main(int argc, char *argv[]) {     obj o;      o.t.timeout();      return 0; } 

this runs fine, had constructor of obj as:

obj() :     t( *this ) 

which results in runtime error. guess because reference member function stored in callback, , not object call member on.

what don't understand std::ref when obj() : t(std::ref(*this)) , why makes program work. can shed light on what's going on , how works ?

when don't pass reference you're copying *this before t has been initialised - means you're copying t , callback member before they've been initialised, undefined behaviour.

(and copy constructor of std::function try copy what's pointed uninitialised pointer, causes actual crash.)


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -