我在一個項目中發現了一段奇怪的代碼,我必須維護它。有一個類的空數組成員,不會導致編譯器錯誤。我測試過的這樣的一些代碼的變化與MSVC 10.0:空數組聲明 - 奇怪的編譯器行爲
template<class T> struct A {
int i[];
}; // warning C4200: nonstandard extension used : zero-sized array in struct/union
template<class T> struct B { static int i[]; };
template<class T> int B<T>::i[];
struct C {
int i[];
}; //warning C4200: nonstandard extension used : zero-sized array in struct/union
template<class T> struct D { static int i[]; };
template<class T> int D<T>::i[4];
template<> int D<int>::i[] = { 1 };
int main()
{
A<void> a;
B<void> b;
C c;
D<void> d0;
D<int> d1;
a.i[0] = 0; // warning C4739: reference to variable 'a' exceeds its storage space
b.i[0] = 0; // warning C4789: destination of memory copy is too small
c.i[0] = 0; // warning C4739: reference to variable 'c' exceeds its storage space
int i[]; // error C2133: 'i' : unknown size
d0.i[0] = 0; // ok
d0.i[1] = 0; // ok
return 0;
}
錯誤消息在int i[]
絕對是明智的我。與類D
一起顯示的代碼是格式良好的標準C++。但是關於類A
,B
和C
?這個類中的成員變量int i[]
是什麼類型的?
問題是:爲什麼警告(與類'A','B'和'C'有關)警告而不是錯誤?在我看來,這與我在局部變量聲明中得到的錯誤相比是不對稱的。 – 0xbadf00d
請參閱我的編輯。 – sergio
謝謝,另一個「漂亮」的微軟擴展到C++標準...... – 0xbadf00d