new、()和[]运算符都在一条指令中
new, () and [] operators all at one instruction
为什么我不能像这样使用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');
相关文章:
- 函数名是c中该函数的第一条指令的地址吗
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 如何在 Win32 中用一条线连接 2 个文本框?
- C++ 如何在同一行中和在一条线上?
- 如何在SDL2窗口上使用Cairo绘制一条白色直线
- 在Opengl中绘制一条不显示C++的线
- 为什么当 while 循环中的 if 条件变为 false 时,我的函数不输出最后一条语句?
- x86 - 为什么编译器在下一条指令中插入看似毫无意义的JMP?
- CMake似乎忽略了一条线
- 在C 中使用Legacy OpenGL(即时模式)绘制一条厚线
- 在图像标签上画一条线并计算距离
- switch 语句结束和下一条语句之间的时间是否具有确定性(与路径无关)
- 如何在OMNET++中收到来自前一个模块的所有消息后将一条消息发送到下一个模块
- char*与上一条指令中设置的值的比较未优化
- new、()和[]运算符都在一条指令中
- 是否可以在一条指令中将4uint8_t复制到4int16中
- 对布尔值的读/写保证是C/C++中的一条指令
- 在C/C++中,左移或右移零点实际上会生成一条指令
- 为什么添加一条从未执行过的指令会导致我的代码性能下降
- 您将如何编写可能优化为一条SSE指令的无符号加法代码