noptr-new-declarator:
[ expression ] attribute-specifier-seq_opt
noptr-new-declarator [ constant-expression ] attribute-specifier-seq_opt不清楚为什么在后一种情况下使用方括号中的允许的constant-expression确切地使用noptr-new-declarator。
如果我们允许分配这样的东西,我看不出关键的东西
int n = 10;
float *fp = new float[5][n];发布于 2014-07-26 16:10:31
编译时:
float* f = new float[2][2];您有以下错误:
无法在初始化时将“float(*)2”转换为“float*”
它解释了new float[2][2]生成了一堆float*[2],而不仅仅是浮点数上的指针。用于存储结果的变量的类型必须在编译时知道其大小,以允许访问数组元素。
如果要执行一些指针算法(在线代码),很容易看出大小取决于非第一个数组大小:
auto f1 = new float[2][10];
std::cout << "F1[0]: " << f1[0] << std::endl;
std::cout << "F1[1]: " << f1[1] << std::endl;
std::cout << "F1[1] - F1[0] : " << f1[1] - f1[0] << std::endl;
auto f2 = new float[2][5];
std::cout << "F2[0]: " << f2[0] << std::endl;
std::cout << "F2[1]: " << f2[1] << std::endl;
std::cout << "F2[1] - F2[0] : " << f2[1] - f2[0] << std::endl;
auto f3 = new float[5][5];
std::cout << "F3[0]: " << f3[0] << std::endl;
std::cout << "F3[1]: " << f3[1] << std::endl;
std::cout << "F3[1] - F3[0] : " << f3[1] - f3[0] << std::endl;该代码输出:
F1[0]: 0x600010480
F1[1]: 0x6000104a8
F1[1] - F1[0] : 10
F2[0]: 0x600048580
F2[1]: 0x600048594
F2[1] - F2[0] : 5
F3[0]: 0x6000485b0
F3[1]: 0x6000485c4
F3[1] - F3[0] : 5所有这些大小都需要在编译时进行计算,这就使得constexpr是强制性的。
https://stackoverflow.com/questions/24972592
复制相似问题