I know I can do new char[n]
to create an array of n
chars. This works even when n
is not a compile time constant.
But lets say I wanted a size variable followed by n chars:
My first attempt at this is the following:
struct Test
{
std::size_t size;
char a[];
};
However it seems new Test[n]
doesn't do what I expect, and instead allocates n
size
s.
I've also found that sizeof(std::string)
is 4 at ideone, so it seems it can allocate both the size and the char array in one block.
Is there a way I can achieve what I described (presumably what std::string
already does)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…