c++ - std::bind a member function to an instance at nullptr causing seemingly random this pointer -


i've tested following program on gcc-4.8 (via coliru) , on visual studio 2013 rc:

#include <iostream> #include <functional>  using namespace std;  struct foo {     void bar() {         cout << "this = " << << endl;     } };  int main() {     try {         foo *ptr = nullptr;         function<void ()> fun = bind(&foo::bar, *ptr);         fun();     } catch (const bad_function_call &e) {         // never reached         cout << "bad_function_call thrown: " << e.what() << endl;     }       cin.get(); } 

i understand i'm causing undefined behavior here dereferencing nullptr, don't understand output of code. in understanding should either cause bad_function_call (because should thrown when calling std::function, guessed) or @ least print "this = 0".

it doesn't. output "this = " followed pointer not nullptr on both compilers tested. accessing causes segmentation fault, though.

is there clause in standard specifying this? or implementation-defined "undefined behavior"?

edit: addition: following code outputs "this = 0" on machine:

foo *ptr = nullptr; ptr->bar(); 

what happens bind stores copy of argument. argument of type foo (since passing *ptr) , hence copy made. copy, of course, gets invalid argument source, not used , hence seems work. result, new instance of foo stored inside bound object , address see.

when see segmentation fault, refer real code, not example gave here, right? in real code guess copy-ctor seems work creates instance causes segmentation fault when access (probably invalid) members.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -