[英]bounded arrays vs unbounded arrays in C++
我偶然發現了std::is_bounded_array
和std::is_unbounded_array
,而且我也知道std::make_unique
不支持有界 arrays。
有人可以更深入地了解為什么會這樣,創建有界數組與創建無界數組有什么區別?
編輯:這與無界數組不同? 因為那里提供的答案集中在無界數組上。 這個問題更側重於實際和實施方面。 創建有界數組和無界數組有哪些不同的方法? 為什么std::make_unique
不支持有界 arrays? 從編譯器的角度來看,有界數組和無界數組有什么不同? 我可以將有界數組轉換為無界數組,反之亦然?
A curious case where bounded vs unbounded arrays arrays is relevant is one of the few cases in C++ where the declared type of an object differs from the declared type of the same object elsewhere . 即,當數組 object 的(不完整)聲明類型是未知邊界數組時,與聲明類型是已知邊界數組時。 來自[basic.types]/6 [強調我的]:
class 類型(例如“class
X
”)可能在翻譯單元中的某個時間點不完整,然后在稍后完成; “classX
”類型在兩個點上都是相同的類型。 數組 object 的聲明類型可能是不完整的 class 類型的數組,因此不完整; 如果 class 類型稍后在翻譯單元中完成,則數組類型變得完整; 這兩個點的數組類型是相同的類型。 數組 object 的聲明類型可能是一個未知邊界數組,因此在翻譯單元中的某個點不完整,稍后完成; 這兩個點的數組類型(“T 的未知邊界數組”和“NT 數組”)是不同的類型。 指向未知邊界數組的指針的類型,或由 typedef 聲明定義為未知邊界數組的類型,無法完成。 [ 例子://... extern int arr[]; // the type of arr is incomplete //... int arr[10]; // now the type of arr is complete
事實上,下面的程序是格式良好的:
#include <type_traits>
// declared type: array of unknown bound (and therefore incomplete)
extern int arr[];
static_assert(std::is_unbounded_array_v<decltype(arr)>);
static_assert(!std::is_bounded_array_v<decltype(arr)>);
// declared type: array of known bound (now the type of arr is complete)
int arr[10];
static_assert(!std::is_unbounded_array_v<decltype(arr)>);
static_assert(std::is_bounded_array_v<decltype(arr)>);
int main() {}
在 C++ 中,“無界數組”更正式地稱為“未知界數組”,同樣,“有界數組”也稱為“已知界數組”。
您不會創建未知邊界的數組 object。 您可以通過 new-expressions 創建不同邊界的 arrays,並使用單個unique_ptr
來管理它們。
std::unique_ptr<int[]> p{new int[3]}; // p manages an array of size 3
p.reset(new int[4]); // now p manages an array of size 4
(在 C++ 中,“數組綁定”和“數組大小”是同義詞。)
提供make_unique
以便您無需直接使用new
。
auto p = std::make_unique<int[]>(3); // p manages an array of size 3
p = std::make_unique<int[]>(4); // now p manages an array of size 4
另一方面,您永遠不需要有界數組的 unique_ptr。 您只需定義數組:而不是std::unique_ptr<int[3]> pointer_to_array;
,您使用int array[3]
。 (實際上, std::unique_ptr<int[3]> p{new int[3]};
格式不正確。)因此std::make_unique
不會嘗試支持這種明顯不存在的用例。
從編譯器的角度來看,有界數組和無界數組有什么不同?
它們只是不同的類型。
我可以將有界數組轉換為無界數組,反之亦然?
沒有也沒有。 沒有隱式或顯式轉換為數組類型。 “已知邊界數組”類型的表達式可以隱式轉換為對未知邊界數組的引用,但是,由於P0388R4 ,指針轉換是可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.