当创建指向 std::queue
的指针并使用 malloc
为其分配内存时,我发现队列的默认大小不是零,如下面的代码所示:
#include <queue>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
std::queue <int> * received_queue = NULL;
received_queue = (std::queue <int > *) malloc (sizeof (std::queue <int>));
printf ("%d\n", received_queue -> size ());
}
返回的结果是:4294967168,我希望得到零。
我用 vector 替换了队列,所以代码变成了:
#include <vector>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
std::vector <int> * received_vector = NULL;
received_vector = (std::vector <int > *) malloc (sizeof (std::vector <int>));
printf ("%d\n", received_vector -> size ());
}
现在返回的结果为0。
我的问题:在分配 std::queue
时我遗漏了什么吗?
最佳答案
malloc
分配一个内存块,但实际上并没有在那里构造一个对象,所以它会包含垃圾。这是您应该使用 new
的原因之一。用 C++ 代替。
如果替换 malloc
用 new std::queue<int>
打电话然后你会看到预期的结果。
如果出于某种奇怪的原因,你需要在内存块中构造一个对象,你可以使用“placement new
”:
new(received_vector) std::vector<int>;
并且还记得在调用 free
之前自己调用析构函数(因为 free
也不调用析构函数)。
关于c++ - malloc 创建时 std::queue 的默认大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052746/