Search code examples
c++shared-ptr

C++ Initialization array handled by boost::shared_ptr


In my class I would like to have some dynamically allocated boolean array. I use shared_ptr to hold it:

boost::shared_ptr<bool[]> someBoolArray;

Memory allocation occurs in class constructor:

// someValue was read from file
someBoolArray = boost::shared_ptr<bool[]>(new bool[someValue]); 

Is it possible to set initial value for my array during shared_ptr initialization?
I want all values in array to be false by default.


Solution

  • If you want to guarantee the elements are set to false, you need an expression of the type

    new T[N]();
    

    In this case,

    someBoolArray = boost::shared_ptr<bool[]>(new bool[someValue]()); 
    //                                                           ^^