【问题标题】:Static Bool Array Not initializing as set静态布尔数组未按设置初始化
【发布时间】:2017-02-20 10:06:13
【问题描述】:

为什么我的静态布尔数组没有正确初始化?只有第一个被初始化 - 我怀疑这是因为数组是静态的。

以下 MWE 是使用 GCC 编译的,并且基于我正在编写的一个函数,该函数已转移到一个主程序中以说明我的问题。我尝试过使用和不使用 c++11。我的理解是因为这个数组是静态的并且初始化为 true 这应该总是在我第一次进入我的函数时打印出来。所以在这个 MWE 中它应该打印一次。

#include <iostream>

using namespace std;

const int arraysize = 10;
const int myIndex = 1;

static bool firstTimeOverall = true;

int main()
{
    static bool firstCloudForThisClient[arraysize] = {true};
    cout.flush();
    if (firstCloudForThisClient[myIndex])
    {
        cout << "I never get here" << endl;
        firstCloudForThisClient[myIndex] = false;
        if (firstTimeOverall)
        {
            firstTimeOverall = false;
            cout << "But think I would get here if I got in above" << endl;
        }
    }
    return 0;
}

【问题讨论】:

  • 是什么让你认为firstCloudForThisClient 的所有元素都初始化为true

标签: c++11 static initialization array-initialization


【解决方案1】:

您可能需要反转条件以利用默认初始化:

#include <iostream>

using namespace std;

const int arraysize = 10;
const int myIndex = 1;  // note this index does not access the first element of arrays

static bool firstTimeOverall = true;

int main()
{
    static bool firstCloudForThisClient[arraysize] = {}; // default initialise
    cout.flush();
    if (!firstCloudForThisClient[myIndex])
    {
        cout << "I never get here" << endl;
        firstCloudForThisClient[myIndex] = true; // Mark used indexes with true
        if (firstTimeOverall)
        {
            firstTimeOverall = false;
            cout << "But think I would get here if I got in above" << endl;
        }
    }
    return 0;
}

【讨论】:

    【解决方案2】:
    static bool firstCloudForThisClient[arraysize] = {true};
    

    这会将第一个条目初始化为 true,将所有其他条目初始化为 false。

    if (firstCloudForThisClient[myIndex])
    

    但是,由于myIndex 为 1 并且数组索引是从零开始的,因此这会访问 second 条目,这是错误的。

    【讨论】:

      【解决方案3】:

      您正在使用 array[size] = {true} 仅初始化数组上的第一个元素,如果 arraysize 变量大于 1,则其他元素的初始值取决于平台。我认为这是一种未定义的行为。

      如果您确实需要初始化数组,请改用循环:

      for(int i=0; i < arraysize; ++i)
      firstCloudForThisClient[i] = true;
      

      【讨论】:

      • 因为这是一个静态变量,用于多次调用的函数中,所以我不能使用循环——这是否意味着我应该把这个函数变成一个对象?
      • 是的,将此功能转换为对象可能很有用。或者您可以将此循环移动到其他函数中并调用一次,例如在程序开始时。如果你非常喜欢静态变量,你甚至可以创建一个静态布尔标志,它可以保护你再次初始化数组。
      • 感谢您的建议 - 我正在尝试使用点云库中的功能获得一些更复杂的线程代码。出于这个原因,我现在将接受您的后一个建议,稍后再接受您的前一个建议(将其变成一个对象)。谢谢!
      • @GoverNator 数组上的列表初始化程序按顺序使用给定的初始化程序,并对其余条目进行值初始化,这意味着所有原语为 0(即布尔值为 false)。它不是未定义的,也不依赖于平台。
      • @user3235290 因为答案不正确,正如我在上面的评论中解释的那样。
      【解决方案4】:

      你应该访问数组的第一个元素,所以使用:

      const int myIndex = 0;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-27
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 2016-10-28
        • 2011-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多