我测试下面的程序上的gcc-4.8(经由Coliru)和Visual Studio中2013 RC:的std ::在nullptr一个成员函数绑定到一个实例引起看似随机的该指针
#include <iostream>
#include <functional>
using namespace std;
struct foo {
void bar() {
cout << "this = " << 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();
}
我理解我通过dereferencing nullptr导致未定义的行为,但我不明白我的代码的输出。根据我的理解,这应该导致bad_function_call(因为这是调用std :: function时应该抛出的东西,根据我的猜测)或者至少打印“this = 0”。
它没有。输出是“this =”,后面跟着一个在我测试的编译器上不是nullptr的指针。但访问它会导致分段错误。
标准中是否有条款说明了这一点?或者它只是实现定义的“未定义的行为”?
编辑:正如加法:下面的代码输出“这一= 0”我的机器上:
foo *ptr = nullptr;
ptr->bar();
所以传递ref(* foo)应该导致“this = 0”成为输出呢?去做一些测试。编辑:它。 –
@DominikLohmann它的确如此。 :) –
分段错误是关于在foo :: bar中访问它。我想知道为什么它不会抛出std :: bad_function_call,因为这将有意义恕我直言。 –