Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

絕對可靠的記憶體配置

此文件需要技術審查。看看您能幫什麼忙。

此文件需要編輯審查。看看您能幫什麼忙。

翻譯不完整。請協助 翻譯此英文文件

There's ongoing work to implement infallible memory allocators. These are memory allocation routines that never return null; that is, they always successfully return the requested block of memory. This is in contrast to a traditional, fallible memory allocator that can return null indicating that the request failed.

Currently, while code is transitioned to be compatible with infallible memory allocators, you have to explicitly decide whether to use infallible allocation or not. Eventually, however, the generic memory allocators (malloc() and realloc()) will become infallible.

記憶體配置要怎樣才能萬無一失?

「萬無一失」這個詞代表了配置記憶體時絕對會成功:你的程式碼永遠不會看到請求失敗,也就無須對失敗的情況做出處置。

平常在配置記憶體時,情況則不太一樣。在有限記憶體的狀況下,記憶體配置是有可能失敗的。然而,在平常配置失敗的程序中程式將不會返回到你的程式碼中,而是直接停止程式。不過這情況可能有點少見,因為記憶體管理系統通常都會為你要求的記憶體想盡辦法找到空間。

選擇記憶體分配器

當你在寫需要配置記憶體的程式時,可能需要遵守幾個規則以便幫助你決定是否在分配器使用萬無一失的策略:

  • 如果你可能需要分配大塊記憶體時,你就應該讓他可能出錯(像是使用 moz_malloc() ,並確保返回的結果不會是 null。就如在 記憶體配置要怎樣才能萬無一失? 一段中所述,在有限的記憶體中要求大塊記憶體時,分配器會找不到你所要求的記憶體,因此程式會直接停止。
  • 如果你不確定記憶體是否會很大塊,就使用標準的 malloc() 來動作,它目前是可能出錯的,但最後可能會變成萬無一失,請確認 null 的結果。
  • 在實例物件時,new 這個運算元預設會萬無一失地創造他們。如果你想要讓他們有機會出錯的話,就使用 new (fallible) Foo() 這個語法。
  • 在有疑慮的時候,使用萬無一失分配器,且不要確認 null 的情況。
  • NS_Alloc() 也是萬無一失的。

明示的萬無一失記憶體分配器

下面的記憶體分配器都明確地標示出他們是萬無一失的,並且會一直保持下去。他們保證會回傳可用的記憶體指標:

p = moz_xmalloc();
p = moz_xrealloc(); 
f = new Foo();
fArray = new Foo[];
n = ::operator new(...);
nArray = ::operator new[](...);

Explicitly fallible memory allocators

These memory allocators are explicitly fallible, and will remain so. When using these, you must check to ensure the resulting value isn't null before attempting to use the returned memory.

p = moz_malloc();
p = moz_realloc(); 
namespace mozilla {
  f = new (fallible) Foo();
  fArray = new (fallible) Foo[];
}
namespace mozilla {
  n = ::operator new(..., fallible);
  nArray = ::operator new[](..., fallible);
}

最終萬無一失分配器

下面的記憶體目前是可能出錯的,但在未來將會變成萬無一失的:

p = malloc();
p = realloc();

你也可以參看

文件標籤與貢獻者

標籤: 
 此頁面的貢獻者: wildsky
 最近更新: wildsky,