new、()和[]运算符都在一条指令中

new, () and [] operators all at one instruction

本文关键字:一条 指令 运算符 new      更新时间:2023-10-16

为什么我不能像这样使用new运算符:

char* p;
p = new char('a')[3];
delete[] p;

编译器说:

error C2143: syntax error : missing ';' before '['
error C3409: empty attribute block is not allowed
error C2143: syntax error : missing ']' before 'constant'

在C++11中,您可以通过新的统一初始化来初始化动态分配的聚合:

p = new char[3] {'a', 'a', 'a'};

在C++98中,不能为动态分配的聚合指定初始值设定项列表。您所能做的就是首先分配数组,然后用一个值填充它:

p = new char[3];
std::fill(p, p + 3, 'a');

在C++11中,您可以说:

char * p = new char[3] { 'a', 'a', 'a' };

在11之前,除了将动态数组初始化为零(或默认值)之外,没有其他方法。在这种情况下,您可以使用std::fill:

#include <algorithm>
std::fill(p, p + 3, 'a');