woosuk
woosuk

Reputation: 221

Cannot push value at priority_queue in the allocated instance

Can anyone explain below code's problem? Thanks

#include <queue>
#include <stdlib.h>
using namespace std;
struct Person {
    priority_queue<int> pq;
};
int main(void) {
    Person* person = (Person*)malloc(sizeof(Person));
    person->pq.push(1);// error here
    return 0;
}

Upvotes: 0

Views: 60

Answers (1)

Pepijn Kramer
Pepijn Kramer

Reputation: 12891

Don't use malloc in C++ (as stated above it will only allocate memory), avoid new and delete if you can.

 #include <queue>
//#include <stdlib.h> <== do not include in C++
#include <memory>

struct Person 
{
    std::priority_queue<int> pq;
};

int main(void) 
{
    Person* person_ptr = new Person();
    person_ptr->pq.push(1);
    delete person_ptr; // with new you have to also write delete or get memory leaks.

    Person person;      // no need to malloc/new, avoid those in C++ as much as you can.
    person.pq.push(1);  

    // Or if you need a pointer do it like this.
    auto person_uptr = std::make_unique<Person>(); 
    person_uptr->pq.push(1);
    // person_uptr's destruction will do the free for us, no memory leaks ;)

    return 0;
}

Upvotes: 1

Related Questions