Search code examples
c++stlflexible-array-member

Is it possible to write a "complete" C++ class with Zero Length Array member?


I have some data type which, if I were to use plain old C, would be implemented as

typedef struct {
    ...many other members here...
    unsigned short _size;
    char           _buf[0];
} my_data; 

What I'd like to do, is to basically make that a class and add the usual operators like less, equality, copy constructor, operator assignment, and so on. As you can imagine I would then be using such class in associative containers like std::map as its key.

I need the buffer to be ideally at the same level of the object itself, otherwise when I have to compare two of them (buffers) I would have the CPU to take the pointer and load it in memory; I don't want to use std::vector because memory allocated wouldn't be contiguous with the rest of the data members.

Main issue for me is the fact that in C I would have a function which, given the size of the buffer would allocate proper memory size for it. In C++ such thing can't be done.

Am I right? Cheers


Solution

  • This is quite impossible. Your object is effectively of variable size but the std::map will always treat it as a fixed size, and there is no way to implement copying or moving. You would need an old C-style container to use such a hack.

    Edit: Custom allocator. Interesting solution, I hadn't thought of that. I don't know if you could make it work but it would be worth looking into.