nested struct with array
-
19-09-2019 - |
Question
Please, help me to create a nested struct with an array. How do I fix this code?
class CMain
{
public:
CMain();
~CMain();
private:
struct
{
CCheckSum() : BufferSize(500) {memset(Buffer, 0, BufferSize);}
const int BufferSize;
char Buffer[BufferSize];
}SmallBuffer;
}
Thanks.
Solution
Static arrays need to know their length at compile time, or you need to dynamically allocate memory:
struct CCheckSum
{
CCheckSum()
: BufferSize(500),
Buffer(new char[BufferSize])
{
memset(Buffer, 0, BufferSize);
}
~CCheckSum() { delete[] Buffer; } // Note the use of delete[]!
const int BufferSize;
char* Buffer;
}SmallBuffer;
You're probably better off using std::vector though:
struct CCheckSum
{
CCheckSum() : Buffer(500, 0) {}
std::vector<char> Buffer; // A std::vector keeps
// track of its size enternally
}SmallBuffer;
OTHER TIPS
Even though you declared BufferSize
as const
, at class scope this does not declare a compile-time constant, which is needed for declaring array sizes in C++, but a constant data member, which, once set in the constructor, cannot be changed anymore for the lifetime of the instance (but can still be different for each instance).
Two solutions: Make
BufferSize
static const
at class scope, or- (just)
const
at namespace scope (including global scope).
There is no problem related to the nesting.
Arrays have constant size. Either make BufferSize constant or use a std::vector instead of a char[].
Array size cannot be changed at run time. It should be known at compile time itself. You can use std::vector for this use case. Also, the struct name should be given before writing the constructor with the name CCheckSum.
struct CCheckSum
{
CCheckSum() : ....