通过 malloc 创建时的默认大小 std::queue

Default size of std::queue when creating it by malloc

当创建指向 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替换了queue,所以代码变成:

#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分配了一个内存块,但是实际上并没有在那里构造一个对象,所以它会包含垃圾。这是您应该在 C++ 中使用 new 的原因之一。

如果您将 malloc 调用替换为 new std::queue<int>,那么您将看到预期的结果。

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

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

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

这不是在 C++ 中创建对象的方式。其实就是Undefined Behaviour。

使用 new 运算符,像这样:

std::vector<int> * received_vector = new std::vector<int>;
std::queue<int> * received_queue = new std::queue<int>;

然后新创建的对象将被正确构造(初始化),因为new导致它们的构造函数被执行。