指针的默认值
Default value of pointer
我已经知道,如果在构造函数中不初始化,则指针成员的值是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
仍然是未定义的行为,但是在大多数平台上,这会触发分割故障。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 具有默认值的引用获取函数
- 为什么在使用指针时不采用类成员的默认值,而不是直接实例化对象时?
- char指针或char变量的默认值是多少
- 指针参数的默认值
- 指针的默认值
- 从指针访问值或获取其默认值(如果为 null)的最干净方法
- 将指针指向函数的函数和将默认值作为参数的向量会导致编译错误
- 将重载函数分配给功能指针作为默认值
- 新的STD :: MAP条目中指针的默认值
- 是指针定义行为映射中 nullptr 的默认值
- 构造函数中指针到指针的默认值存在问题
- 将包装器与函数指针一起使用来处理参数的默认值
- Howto:c++函数指针与默认值
- 如何在编译时通过模板形参默认值的名称/指针获取函数的类型
- 指针对成员函数默认值出现与CRTP相关的编译器错误
- 构造函数中指针的默认值是什么意思?
- C++结构中指针的默认值
- 将函数指针上的参数与默认值参数一起丢弃是否有效
- C++中函数指针的默认值