Reputation: 57
I have at the beginning of the code boost::shared_array<uint8_t> buffer(new uint8_t[fileSize]);
. I want to change that as size
will be read from a file. Therefore, how can I just declare boost::shared_array<uint8_t> buffer
and allocate the size after I read it?
I am reading the file with:
size_t fileSize;
union size{
uint8_t size_arr[4];
uint32_t size;
} size;
if (myfile.is_open()){
while ( getline (myfile,line) ){
if(lineNum==1)
size.size_arr[0] = strtoul(line.c_str(), 0 , 16);
if(lineNum==2)
size.size_arr[1] = strtoul(line.c_str(), 0 , 16);
if(lineNum==3)
size.size_arr[2] = strtoul(line.c_str(), 0 , 16);
if(lineNum==4) {
size.size_arr[3] = strtoul(line.c_str(), 0 , 16);
fileSize = size.size;
//boost::shared_array<uint8_t> buffer(new uint8_t[stringFromFile_size]); //CANNOT be done here
}
if(lineNum>=5)
size.size_arr[lineNum-1] = strtoul(line.c_str(), 0 , 16);
lineNum++;
}
myfile.close();
}
Of course if I declare it in the if for lineNum==4
I cannot use buffer
outside the while loop which is the goal.
Thank you for the help.
Upvotes: 0
Views: 202
Reputation: 29985
Use std::unique_ptr
or std::shared_ptr
:
std::unique_ptr<uint8_t[]> buffer; // note []
// std::shared_ptr<uint8_t[]> buffer;
// get size
size_t sz = ...;
buffer.reset(new uint8_t[sz]); // allocate memory
Upvotes: 1