Search code examples
c++stlpushpriority-queue

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;
}

Solution

  • 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;
    }