2013-11-02 38 views
1

考慮下面這個簡單的函數聲明:返回的值 - 錯誤指示值

vector<Date> getMonthArray(int month, int year); 

至於C++ 11,我可以利用移動語義的和值,而不損失任何性能的返回日期矢量和避免使用'新'和'刪除'。

問題是,如果功能失敗,則不知道該返回什麼。 E.G.一個月或一年都低於零

我都不能返回null,因爲我可以用指針做, 所以我想到了兩種可能性:

1)返回一個空數組 2)拋出一個異常

說實話,我討厭這兩個。很想聽聽更有經驗的C++程序員的更好的解決方案。

編輯:

所以,拋出一個異常,真的看起來像最優雅的解決方案,因爲它不涉及用戶的需要,爲了正常運行的功能(可拋出的異常,除了閱讀任何文件)。我對麼?或者其他更多的選擇?

+0

在此處拋出異常是要走的路。 – rightfold

+0

@rightfold:護理闡述?在這種情況下,你怎麼可能知道什麼是OP的「正確」解決方案?異常處理可以是一個棘手的野獸,然後有各種各樣的關於在哪裏檢查異常,這也正是他們應該處理的問題。也許對於有機磷農藥代碼的最好的事情就是打電話getMonthArray之前驗證輸入,因爲他們可以,然後有依賴於該驗證的輸入等功能。我的觀點是,不知道OP的代碼庫,稱「使用例外」需要配備大量的鹽。 – AndyG

回答

0

如果它可能失敗,一個空向量不是一個可怕的想法。人們似乎喜歡返回錯誤代碼的一種方法就是將該向量作爲參考參數,並將函數的返回值更改爲布爾值,或者如果返回代碼類型更多,則返回int(可以是枚舉類型,太)。根據返回的值,不同的條件可能適用於您的矢量。我認爲在這種情況下,儘管一個空的向量可以很好地記錄下來。參考參數,布爾返回方法的錯誤代碼

//pre: none 
//post: if month and year are valid, monthArray will contain array 
//  of months and function returns true. 
//  Otherwise returns false with no guarantees on contents of monthArray 
bool getMonthArray(int month, int year, vector<Date>& monthArray); 

實施例中,參考參數

//pre: none 
//post: if month and year are valid, monthArray will contain array 
//  of months and function returns 0 for success. 
//  If month is valid but year is not, returns -1 
//  If month is invalid, but year is not, returns -2 
//  If month and year are valid, but otherwise failed, returns -3 
int getMonthArray(int month, int year, vector<Date>& monthArray); 
0

簡單的

實施例,通過將載體和成功返回bool

bool getMonthArray(std::vector<Date>* out, int month, int year); 

在您的實現中,如果參數無效,則返回false。

1

有極少數的選擇:

  1. 返回指示錯誤的正常返回類型的特殊價值。
  2. 更改返回到錯誤代碼(或標誌)並具有輸出參數(參考或指針)。
  3. 返回既包含值又包含錯誤指示符的包裝(例如:Boost.Optional)。
  4. 拋出異常。
  5. 有無法無效的參數。

選項1到4是非常明顯的。

選項5並不總是可能的,但參數類型(包括枚舉),並解釋仔細選擇在某些情況下工作。

不知道你的功能在做什麼,這裏有一些建議:

a。改變月份&一年的類型爲unsigned。 b。將「月」解釋爲連續的:

vector<Date> getMonthArray(unsigned int month, unsigned int year) { 
    year = year + month/12; 
    month = month % 12; 
    ...