前段時間,我建議我使用std :: vector作爲C++中的異常安全動態數組,而不是分配原始數組......例如在空std :: vector上使用運算符[]
{
std::vector<char> scoped_array (size);
char* pointer = &scoped_array[0];
//do work
} // exception safe deallocation
我已經使用這個約定多次,沒有任何問題,但是我最近移植一些代碼的Win32 VisualStudio2010(以前是隻能在MacOS/Linux的)和我單元測試打破(STDLIB拋出斷言)當矢量大小恰好爲零時。
我知道寫入這樣一個數組會是一個問題,但是這個假設破壞了這個解決方案作爲原始指針的替代。考慮下面的功能與n = 0的
void foo (int n) {
char* raw_array = new char[n];
char* pointer = raw_array;
file.read (pointer , n);
for (int i = 0; i < n; ++i) {
//do something
}
delete[] raw_array;
}
雖然可以說是多餘的,上面的代碼完全合法(I相信),而下面的代碼將拋出VisualStudio2010
void foo (int n) {
std::vector<char> scoped_array (n);
char* pointer = &scoped_array[0];
file.read (pointer , n);
for (int i = 0; i < n; ++i) {
//do something
}
}
斷言當時我一直在使用未定義的行爲?我在印象運算符[]下沒有檢查錯誤,這是對std :: vector <>的有效使用。有其他人遇到過這個問題嗎?
- 編輯: 感謝所有有用的回覆,回覆人們說這是未定義的行爲。 有沒有辦法取代上面的原始數組分配將與n = 0?
雖然說檢查n = 0作爲例外情況將解決問題(它會)。有許多模式不需要特殊情況(比如上面的原始指針示例),因此可能需要使用除std :: vector <以外的東西?
拋出哪個異常?我沒有看到代碼錯誤。 – fschmitt 2010-09-30 10:45:00
@fschmitt:如果向量爲空,那麼'scoped_array [0]'給出未定義的行爲。在這種情況下,使用Visual C++構建一個調試變體,它會失敗範圍檢查並引發異常。 – 2010-09-30 11:28:15
@fschmitt:std :: vector的visual studio實現會觸發一個斷言(即立即終止整個過程),並顯示一個錯誤,說明向量上出現了一個越界錯誤。 – Akusete 2010-09-30 11:33:16