malloc创建std::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 ("%dn", received_queue -> size ());
}

返回的结果是:4294967168,我期望得到零。

我用矢量替换了队列,所以代码变成:

#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 ("%dn", received_vector -> size ());
}

现在返回的结果是0。

我的问题是:在分配std::queue时是否遗漏了什么?

malloc分配了一个内存块,但实际上并没有在那里构造对象,因此它将包含垃圾。这也是您应该在C++中使用new的原因之一。

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

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

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

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

这不是在C++中创建对象的方法。事实上,这是未定义的行为。

使用new运算符执行此操作,如下所示:

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

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

最新更新