簡體   English   中英

通過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 ++創建對象的方法。 實際上,這是未定義的行為。

使用new運算符執行此操作,如下所示:

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

然后,新創建的對象將被正確地構造(初始化),因為new導致其構造函數被執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM