指针

时间:2018-03-29 06:17:14

标签: c++ g++ clang++

如果没有在构造函数中初始化,我已经知道类的指针成员的值是undefined(参考this question)。我做了一个简单的例子来测试它。

main.cc

#include <iostream>

class Foo {
public:
    Foo() {
        std::cout << __FUNCTION__ << std::endl;
        count = 10;
    }

    void test() {
        std::cout << __FUNCTION__ << count << std::endl;
    }

private:
    int count;
};

class Bar {
public:
    void bar() {
        std::cout << __FUNCTION__ << std::endl;
        std::cout << m_foo << std::endl;
        m_foo->test();
        m_foo = new Foo();
        std::cout << m_foo << std::endl;
    }

private:
    Foo *m_foo;
};


int main(int argc, char *argv[])
{
    std::cout << __FUNCTION__ << std::endl;
    Bar bar;
    bar.bar();
    return 0;
}

如果我使用g++

g++ -std=c++11 main.cc -o test

按预期运行错误:

main
bar
0
Segmentation fault

但是,如果我改为使用clang++进行编译:

clang++ -std=c++11 main.cc -o test

它运行时没有任何错误:

main
bar
0x400920
test-1991643855
Foo
0x1bf6030

如您所见,虽然指针未初始化,但它的地址不是NULL,它可以正常调用函数test。如何使用clang++阻止此错误?

1 个答案:

答案 0 :(得分:1)

没有&#34;默认值&#34;指针。 m_foo未初始化,期间。因此解除引用它是未定义的行为。请注意&#34;未定义的行为&#34;包括&#34;显然工作正常&#34;。

像这样声明m_foo

Foo * m_foo = nullptr;

取消引用nullptr仍然是未定义的行为,但在大多数平台上,这将触发分段错误。

相关问题