Reputation: 19
I want to employ a queue as a member of struct, but the following code goes wrong when run it.
#include "stdafx.h"
#include <math.h>
#include <stdio.h>
#include <queue>
typedef struct {
int a;
std::queue <int> b;
}Qtest;
int main(void)
{
char *WorkingBuffer = NULL;
WorkingBuffer = (char *)malloc(sizeof(Qtest));
Qtest *st = (Qtest *)WorkingBuffer;
std::queue<int> c;
c.push(1);
st->a = 0;
st->b.push(1);
return 0;
}
However, if I define a queue out of the struct, it can work. I have no idea about this, can anyone give me some advice?
Upvotes: 0
Views: 354
Reputation: 11
This is the difference between malloc
/free
and new
/delete
. malloc
only allocates memory without calling the constructor. Meanwhile, the new
operator allocates memory and and calls the constructor. This is almost always what you want in C++ and so you should only use malloc
in very low-level code.
Upvotes: 1