在我們的代碼庫中,我們不使用C++異常,意思是「-fno-exceptions
」在gcc編譯選項中(請注意這是我們公司的政策,所以不需要爭論)。然而,在這種情況下,如何從引發異常的標準庫中檢查構造函數的失敗。我已經閱讀了一些SO帖子,但仍然沒有明確的想法。例如,在C++ 11中,std::regex("pattern")
可以拋出regex_error異常。如果我有下面的代碼:如何檢查構造函數失效,例外情況禁用
class Wrapper {
public:
bool create(std::string pattern) {
try {
m_regex = std::regex(pattern);
m_state = true;
} catch (std::regex_error& e) {
//handle error case
m_state = false;
}
}
private:
std::regex m_regex;
bool m_state;
}
注: m_regex = std::regex(pattern);
將調用
explicit basic_regex(const CharT* s, flag_type f = std::regex_constants::ECMAScript)
會拋出異常和移動賦值運算符現在
basic_regex& operator=(basic_regex&& __rhs) noexcept
,沒有選擇使用異常,我們如何檢查失敗o f std :: regex的構造函數?
class Wrapper {
public:
create(std::string pattern) {
m_regex = std::regex(pattern);
// now, how to check?
// if (m_regex)?
m_state = true;
}
private:
std::regex m_regex;
}
我沒有找到在std :: regex中有任何狀態可以指示失敗。
選項1:我可以假設如果正則表達式構造函數失敗,會發生abort(),那麼下面的語句m_state = true
將不會被執行?我查了一下,看起來abort()通常發生在異常啓用的情況下,但沒有使用catch。所以這是錯誤的。
選項2:我可以使用std::regex* ptr_regex = new std::regex("pattern")
,檢查ptr_regex的NULL的含量?
你不能。如果你不允許使用異常(即使只是爲了捕獲),你必須避免使用STL。 – Gonmator
正如@Gonmator所說的,除了它不僅僅是STL:你必須避免大部分C++標準庫的每個部分,特別是正則表達式。 –
對於「我們公司不允許例外」的一個很好的解決方案,除非是因爲非常好的原因,例如資源非常低的嵌入式編程,或者處理遺留代碼庫(這是谷歌的方式),是如果可能的話,在別處找工作。因爲,一個由不稱職者制定的重要政策,其餘的可能就是一樣糟糕。例如,同樣適用於例如首席執行官表示缺乏職業道德指南針:這可能影響了幾乎所有的組織。 –