C++中未设置布尔值的默认值

Default value of an unset boolean in C++?

本文关键字:默认值 布尔值 设置 C++      更新时间:2023-10-16

可能重复:
为什么C++布尔变量默认为true?

假设我要做这样的事情:

class blah
{
  public:
  bool exampleVar;
};
blah exampleArray[4];
exampleArray[1].exampleVar = true;

在exampleArray中,exampleVar现在有3个未设置的实例,如果没有我设置它们,它们的默认值是多少?

默认值取决于exampleArray在其中声明的作用域。如果它是函数的本地值,则值将是随机的,无论这些堆栈位置所在的值是什么。如果它为静态值或在文件作用域(全局(声明,则值都将初始化为零。

这是一个演示。如果需要成员变量具有确定性值,请始终在构造函数中初始化它。

class blah
{
  public:
  blah() 
  : exampleVar(false)
  {}
  bool exampleVar;
};

编辑:
上面例子中的构造函数在C++11中不再是必需的。数据成员可以在类声明本身中初始化。

class blah
{
  public:
  bool exampleVar = false;
};

如果需要,此内联默认值可以由用户定义的构造函数重写。

struct x
{
    bool b;
    x() : b() { }
}
...
x myx;

在这种情况下,myx.b将为false。

struct x
{
    bool b;
}
...
x myx;

在这种情况下,myx.b将是不可预测的,它将是内存位置在分配myx之前的值。

由于在C和C++中,假值被定义为0,真值被定义成非零,因此随机地址位置包含真值而不是假值的可能性更大。通常,在C++中,sizeof(bool(是1,意思是8位。内存的随机位置有255种可能是错误的,这就解释了为什么你认为默认的布尔值是真的。

它们的默认值是未定义的。你不应该依赖于它们被设置为这样或那样的东西,它通常被称为"垃圾"。

根据编译器的不同,它可能设置为false。但即便如此,你还是最好把它们放在一边。

不确定。

非静态成员变量需要初始化,除非您可以保证对它们执行的第一个操作是写操作。最常见的方法是通过构造函数。如果您仍然想要无arg/no-op构造函数,请使用初始化列表:

public:
blah() : exampleVar(false) {}

默认值为不确定。每次运行程序时可能会有所不同。您应该将值初始化为某个值,或者使用另一个变量来指示您的私有成员未初始化。

@Praetorian:涵盖了他回答的要点。

但同样值得注意的是。

blah exampleArray[4];         // static storage duration will be zero-initialized 
                              // ie POD member exampleVar will be false.
void foo()
{
    blah exampleArray1[4];    // automatic storage duration will be untouched.
                              // Though this is a class type it only has a compiler 
                              // generated constructor. When it is called this way 
                              // it performs default-construction and POD members
                              // have indeterminate values

    blah exampleArray2[4] = {};  // Can force zero-in initialization;
                                 // This is list-initialization.
                                 // This forces value-initialization of each member.
                                 // If this is a class with a compiler generated constrcutor
                                 // Then each member is zero-initialized

    // following through to non array types.
    blah       tmp1;            // Default initialized: Member is indeterminate
    blah       tmp2 = blah();   // Zero Initialized: Members is false
    // Unfortunately does not work as expected
    blah       tmp3();          // Most beginners think this is zero initialization.
                                // Unfortunately it is a forward function declaration.
                                // You must use tmp2 version to get the zero-initialization 
}

未分配的默认值在C/C++中是未定义的。如果您需要一个特定的值,那么为类blah创建一个构造函数并设置默认值。