views:

233

answers:

4

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.

A: 

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;
luke
I intended to use array because I need to fill it with consecutive blocks of raw data bytes. Push_back() it will cause reallocation which I want to avoid. If I declare a vector of 500 bytes how do I copy, say , blocks of 100, 200 and 200 bytes into it one after another without putting them byte-by-byte with [] operator?
Jack
Actually, come to think of it, `std::(tr1::)array`, not `std::vector` is the correct thing to use here, since the size is (supposed to be) a compile-time constant.
luke
If he has access to it, std::(tr1::)array is a good choice too. If not, vector is the way to go.
luke
A: 

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[].

AProgrammer
But I declared BufferSize as const int. And I use raw buffer since I need to do some simple and quick work with raw data coming from network.
Jack
You need to make it static as well.
AProgrammer
A: 

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() : ....
aJ
+2  A: 

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

  1. BufferSize static const at class scope, or
  2. (just) const at namespace scope (including global scope).