c++ - malloc 创建时 std::queue 的默认大小

标签 c++ vector queue

当创建指向 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++ 代替。

如果替换 mallocnew std::queue<int> 打电话然后你会看到预期的结果。

如果出于某种奇怪的原因,你需要在内存块中构造一个对象,你可以使用“placement new”:

new(received_vector) std::vector<int>;

并且还记得在调用 free 之前自己调用析构函数(因为 free 也不调用析构函数)。

关于c++ - malloc 创建时 std::queue 的默认大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052746/

相关文章:

javascript - 当一个已经运行时如何处理返回 promise ?

c++ - 在 Cuda 中使用二维数组数据成员

html - 如何使用 libMongoose/Embedded Mongoose 发送 HTML 和图像?

c++ - 将元组的 const 引用传递给仿函数

c++ - 如何检查空行?

c++ - move std::vector 的 std::unique_locks

c++ - std::vector<unsigned char> 到 QPixmap

c++ - 试图向现有 std::vector 添加元素的堆损坏

javascript - Node.js - async.queue() - 如何结束任务以允许更多任务运行?

c++ - 我们如何在 C++ 实现文件中包含结构?