无法在分配的实例中推送 priority_queue 处的值
Cannot push value at priority_queue in the allocated instance
谁能解释一下下面代码的问题?
谢谢
#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;
}
不要在 C++ 中使用 malloc(如上所述,它只会分配内存),如果可以,请避免使用 new 和 delete。
#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;
}
谁能解释一下下面代码的问题? 谢谢
#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;
}
不要在 C++ 中使用 malloc(如上所述,它只会分配内存),如果可以,请避免使用 new 和 delete。
#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;
}