mas*_*sti 5 c++ malloc new-operator
在C(使用gcc)中,我可以声明一个变长结构,如下所示:
typedef struct ProtocolFrame
{
uint8_t op;
uint32_t address;
uint16_t size;
uint8_t payload[0];
} ProtocolFrame;
Run Code Online (Sandbox Code Playgroud)
然后我可以分配不同的框架:
ProtocolFrame *frA;
ProtocolFrame *frB;
frA = malloc(sizeof(ProtocolFrame) + 50);
frB = malloc(sizeof(ProtocolFrame));
Run Code Online (Sandbox Code Playgroud)
在此示例中,frA具有大至50字节的有效载荷字段,并且frB没有有效载荷
我可以使用new运算符在C++中做同样的事情吗?
template<size_t s>
struct ProtocolFrame
{
uint8_t op;
uint32_t address;
uint16_t size;
uint8_t payload[s];
} ProtocolFrame;
// specialize for no payload
template<>
struct ProtocolFrame<0>
{
uint8_t op;
uint32_t address;
uint16_t size;
} ProtocolFrame;
ProtocolFrame<50> *frA = new ProtocolFrame<50>;
ProtocolFrame<0> *frB = new ProtocolFrame<0>;
Run Code Online (Sandbox Code Playgroud)
要确定运行时的大小,您可以使用placement-new运算符与std::malloc
:
void *buffer = std::malloc(sizeof(ProtocolFrame)+50);
ProtocolFrame *frA = new (buffer) ProtocolFrame;
Run Code Online (Sandbox Code Playgroud)
您还可以在codeproject.com上阅读本文,其中包含完整示例.