Is there a standard way to replace a C-style bool array?

白昼怎懂夜的黑 提交于 2020-01-03 17:26:06

问题


In this piece of code

void legacyFunction(int length, bool *bitset)
{
    // stuff, lots of stuff
}

int main()
{
    int somenumber = 6;
    // somenumber is set to some value here

    bool *isBitXSet = new bool[somenumber];
    // initialisation of isBitXSet.

    legacyFunction(somenumber, isBitXSet);

    delete[] isBitXSet;
    return 0;
}

I'd like to replace bool *isBitXSet = new bool[somenumber]; by something like

std::vector<bool> isBitXset(somenumber, false);

But I cannot do

legacyFunction(somenumber, isBitXSet.data());

because data() doesn't exist for std::vector<bool>. And I cannot change the interface of legacyFunction().

Is there a good alternative to the C-style bool array?


回答1:


You can use std::unique_ptr<T[]> and std::make_unique:

int main()
{
    int somenumber = 6;
    // somenumber is set to some value here

    auto isBitXSet = std::make_unique<bool[]>(somenumber);    
    // initialisation of isBitXSet.

    legacyFunction(somenumber, isBitXSet.get());

    return 0;
}

Alternatively, you can "trick" std::vector by creating your own bool wrapper:

struct my_bool { bool _b; };
std::vector<my_bool> v; // will not use `vector<bool>` specialization

If you know the size of your array at compile-time, consider using std::array.



来源:https://stackoverflow.com/questions/46115237/is-there-a-standard-way-to-replace-a-c-style-bool-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!