4

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?

4
  • 1
    Note that the missing data() member function is not the only problem. std::vector<bool> is a specialization that may provide a more space-efficient implementation. So the elements of vector<bool> and a C-style bool array may not overlap. Commented Sep 8, 2017 at 11:33
  • Possible duplicate of Alternative to vector<bool> Commented Sep 8, 2017 at 11:33
  • @moooeeeep Yeah, right, sorry. Normally I would delete the question by myself. But I like the answer given by Vittorio Romeo much more than any of those answers from 2009. Commented Sep 8, 2017 at 11:40
  • No need to worry. I just wanted to have them linked and thought they might be related close enough to have them as duplicate. Others might disagree. Commented Sep 8, 2017 at 12:42

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Isn't std::array also a possibility?
@Rakete1111: not if somenumber is a run-time value, as in the example.
Nice answer! In your second example: How would I apply this to make the function call? Like this legacyFunction(somenumber, reinterpret_cast<bool*>(v.data()));?
@TobiMcNamobi: that will probably work but I am unsure about its safety and standard-compliance. Only use that after proper research. I would suggest going with unique_ptr.
@TobiMcNamobi How about legacyFunction(somenumber, &v[0]); ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.