考虑:
delete new std :: string [2];
delete [] new std :: string;
众所周知,第一个是错误的。如果第二个不是错误的,我们就不需要两个不同的运算符了。
现在考虑:
std :: unique_ptr <int> x (new int [2]);
std :: unique_ptr <int> y (new int);
x
是否知道使用 delete[]
而不是 delete
?
背景:当我想到指针的数组类型限定符可能是一种方便的语言特性时,这个问题浮现在我的脑海中。
int *[] foo = new int [2]; // OK
int * bar = new int; // OK
delete [] foo; // OK
delete bar; // OK
foo = new int; // Compile error
bar = new int[2]; // Compile error
delete foo; // Compile error
delete [] bar; // Compile error
new int [2]
应该返回类型为int (*)[2]
的值。无论如何,现在修复本地数组的所有问题为时已晚,但您可以使用std::array
并避免处理它们。std::array
的工作方式类似于本地数组应该工作的方式,您永远不必使用new[]
或delete[]
。 - bames53std::array
有一个限制。你可以使用new int[n]
,但是你不能使用std::array<int,n>
(除非在编译时已知n
)。但是,我仍然避免使用原生数组!# - Aaron McDaidstd::vector
。 - bames53