Ryuk
Ryuk

Reputation: 19

cannot use queue as a member of struct in C++

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

Answers (1)

potter lv
potter lv

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

Related Questions