簡體   English   中英

我應該對非常大的 arrays 使用 std::array 嗎? 什么是慣用的替代方法?

[英]Should I be using std::array for very large arrays? What is the idiomatic alternative?

我正在用 C++ 做大學作業。 我主要是在 C 中得到指導,所以我正在努力練習更“慣用的”C++。

在 C 中,我使用大型動態分配數組沒有問題:

int* board = (int*) malloc(2048 * 2048 * sizeof(int));

據我了解,在malloc中,不應該使用 malloc ,也不應該使用newdelete ,而 RAII 才是王道。 與其自己擔心 memory 的分配和釋放,我更願意使用 STL。

但是,此代碼不會運行(但會編譯):

std::array<int, 2048 * 2048> board;

使用 Valgrind,我注意到試圖在堆棧上分配的 memory 的數量(大約 840 萬個int s)遠遠超出了操作系統的意願。

C++ 與大型 arrays 一起工作的方式是什么?

一般來說,來自 C:

  • int foo[10] -> std::array<int, 10> foo
  • int* foo = malloc(10 * sizeof(int)) -> std::vector<int> foo(10)

std::array直接包含其所有元素,就像 C 數組一樣。 實際上,它本質上只是這樣的簡單結構:

template <typename T, size_t N>
struct array
{
    T __unspecified_name[N];

    // Some member functions
};

另一方面, std::vector為其元素動態分配存儲,就像您手動使用malloc 它只是在需要時自動管理重新分配更多存儲空間,並在其析構函數中釋放其分配的存儲空間。


malloc的另一種替代方法是智能指針,例如std::unique_ptr<int[]> foo = std::make_unique<int[]>(10) 這在某些特定情況下很有用(即,當 memory 或代碼大小非常緊湊,或者您特別想要只移動語義時)。 這有點偏離了觀點,但是如果您沒有特定理由使用其他東西,IMO 通常應該更喜歡std::vector

暫無
暫無

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

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