我想在我的構造函數中拋出異常,這樣我就不必處理殭屍對象。不過,我也希望提供一種驗證方法,以便人們可以避免在沒有理由的情況下「處理例外情況」。在GUI中,它不是例外以期望無效數據。不過,我也想避免代碼重複和開銷。 GCC/Microsoft Visual C++編譯器是否足夠聰明,可以消除驗證輸入兩次的低效率,如果沒有,是否有可能取悅的微妙變化?C++:如果所有數據可能已經有效,那麼在構造函數中驗證是否有開銷?
一個例子代碼塊說明我的觀點是如下:
#include <string>
#include <exception>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
using std::exception;
// a validation function
bool InputIsValid(const string& input) {
return (input == "hello");
}
// a class that uses the validation code in a constructor
class MyObject {
public:
MyObject(string input) {
if (!InputIsValid(input)) //since all instances of input
throw exception(); //has already been validated
//does this code incur an overhead
//or get optimised out?
cout << input << endl;
};
};
int main() {
const string valid = "hello";
if (InputIsValid(valid)) {
MyObject obj_one(valid);
MyObject obj_two(valid);
}
return 0;
}
我預計,這可能不是可能,如果是單獨生成的對象的類文件作爲對象文件沒有辦法,以確保人們將驗證在調用構造函數之前,但是當一個應用程序被編譯並且在一個應用程序中鏈接在一起時,請問可以嗎?
你的編譯器可以吐出彙編代碼,你可以看看它是否被優化了。 – 2012-06-23 18:24:25
相反,用try-catch塊替換'main()'中的if語句可能更好。 – 2012-06-23 18:24:44
考慮到你複製了一個用於初始化MyObject的字符串,我非常懷疑重複檢查的開銷會讓你擔心。除非你的字符串實現_SSO_並且你只使用幾個字符的字符串。 –