2012-03-20 68 views
10

下面的簡單程序片段給出編譯錯誤gcc-4.3.4正在分配一個動態數組而不指定大小格式良好的代碼?

計劃:

int main() 
{ 
    char *ptr = new char[10];  
    char *ptr1 = new char[];  
    return 0; 
} 

編譯錯誤:

prog.cpp: In function ‘int main()’:
prog.cpp:4: error: expected primary-expression before ‘]’ token
prog.cpp:3: warning: unused variable ‘ptr’
prog.cpp:4: warning: unused variable ‘ptr1’

但同樣與MSVC完全編譯沒有任何診斷信息。

所以我的問題是:
是否標準允許在不指定sizenew []被稱爲?或者這是MSVC中的錯誤?
有人可以提供一個標準的參考,它將確鑿地說,上面的代碼示例是不合格或格式良好?


我有一個看看:

5.3.4新[expr.new] &
18.4.1.2數組形式[lib.new.delete.array]

但無法找到任何有關該行爲的確鑿證據。


編輯:
添加Language Lawyer標籤。
我期待着觀察到的行爲的答案,無論它是否有用,我完全意識到它沒有用,也不推薦。

+1

如果這是合法的,我沒有看到它的重點... – Mehrdad 2012-03-20 05:27:39

+2

我不明白它是如何可以形成良好的代碼?編譯器要做什麼,猜測大小?這似乎相當困難(如果不是不可能的話)。 – Corbin 2012-03-20 05:27:45

+3

+1,有趣,等待一個很好的答案。 – ApprenticeHacker 2012-03-20 05:30:08

回答

4

這在語法上不正確。

看看syntax新表達式

noptr-新聲明符必須包含在方括號之間的表達表達必須在它有一個令牌。

4

這不是合法的C++。

5.3.4新[expr.new]說明了什麼是合法的方式在一個大名單,其中包含此行調用新:

noptr-new-declarator: 
     [ expression ] attribute-specifier-seqopt 
     noptr-new-declarator [ constant-expression ] attribute-specifier-seqopt 

,後來它解釋了常量表達式可以是什麼(在5.4.3/6和5.4中。3/7):

Every constant-expression in a noptr-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value.


後的一些想法,下一個項目應初步認識:

8.3.4/1 [dcl.array],包括以下部分:

In a declaration T D where D has the form

D1 [ constant-expressionopt ] attribute-specifier-seqopt 

and the type of the identifier in the declaration T D1 is 「derived-declarator-type-list T」, then the type of the identifier of D is an array type;

if the constant expression is omitted, the type of the identifier of D is 「derived-declarator-type- list array of unknown bound of T」, an incomplete object type.

5.3.4/1講述:

This type shall be a complete object type, but not an abstract class type or array thereof

既然你省略數組的大小,類型是不完整的,並且你的程序是不是合法的C++。

+0

第一行的怎麼辦? 用於多維數組。例如'x = new char [plop * 5/* expression * /] [10/* const-expression * /] [100/* const-expression * /]' – 2012-03-20 06:08:55

+0

匆匆一瞥,我看不到是空的, ? – 2012-03-20 06:11:06

+0

@LokiAstari這就是爲什麼我添加了* constant-expression *可以編輯的原因:* noptr-new-declarator中的每個常量表達式應該是一個整型常量表達式*。由於它在問題中被省略,所以它不是一個標準的C++,而是一個編譯器擴展。這不是UB,因爲它編譯,但它不應該。 – 2012-03-20 06:18:22