指针的默认值

Default value of pointer

本文关键字:默认值 指针      更新时间:2023-10-16

我已经知道,如果在构造函数中不初始化,则指针成员的值是undefined(请参阅此问题(。我做了一个简单的示例来测试它。

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++防止此错误?

指针没有"默认值"。m_foo不是初始化的,期限。因此,请说明这是不确定的行为。请注意,"未定义的行为"包括"显然工作正常"。

像这样声明m_foo

Foo * m_foo = nullptr;

删除nullptr仍然是未定义的行为,但是在大多数平台上,这会触发分割故障。