相关疑难解决方法(0)

何时在null实例上调用成员函数会导致未定义的行为?

请考虑以下代码:

#include <iostream>

struct foo
{
    // (a):
    void bar() { std::cout << "gman was here" << std::endl; }

    // (b):
    void baz() { x = 5; }

    int x;
};

int main()
{
    foo* f = 0;

    f->bar(); // (a)
    f->baz(); // (b)
}
Run Code Online (Sandbox Code Playgroud)

我们期望(b)崩溃,因为x空指针没有相应的成员.在实践中,(a)不会崩溃,因为this从不使用指针.

因为(b)取消引用this指针((*this).x = 5;),并且this为null,程序进入未定义的行为,因为取消引用null总是被称为未定义的行为.

(a)导致未定义的行为吗?如果两个函数(和x)都是静态的呢?

c++ standards-compliance null-pointer undefined-behavior language-lawyer

115
推荐指数
2
解决办法
1万
查看次数

函数调用返回null对象时返回的布尔值

在C++中对空对象进行fucntion调用时返回的布尔值是多少?

ClassDummy* dummy = NULL;
if (!dummy->dummy_function(1,2,3)) {
  // Do Something
}
Run Code Online (Sandbox Code Playgroud)

根据C++ 11标准,这不应该返回错误吗?

c++ c++11

5
推荐指数
2
解决办法
284
查看次数