2017-06-04 112 views
-4

在我的代碼中,有時候會有一個很長的函數,爲了避免混淆局部變量,我會用一對大括號來包含細節,這樣局部變量對其餘部分將不可見代碼,例如:如何隱藏局部變量

bool pricing_deals() 
{ 
    //prepare deal type lookup table 
    vector<DealType> deal_types; // deal type lookup table 
    { 
    vector<DealType> deal_types_TRF; 
    vector<DealType> deal_types_DCI; 
    ... 
    // code that prepare deal_types by merging deal_types_TRF and deal_types_DCI etc 
    } 
    // from now on deal_types_TRF and deal_types_DCI are invisible 

    //prepare ccy pair lookup table 
    vector<CcyPair> ccy_pairs; // ccy pair lookup table 
    { 
    // code that prepare ccy_pairs; 
    } 
    // from now on local variables preparing ccy_pairs are invisible 

    // real computation starts 
    ... 
} 

我不知道這是一個很好的做法,還是有這樣做你會suggeset的其他方式?

p.s.在這種情況下,我不希望將其分解爲更小的函數,因爲子邏輯不太可能被其他人重用,而重構會導致大量參數被傳遞,這會增加複雜性。

+0

你沒看到「請勿使用!」在[tag:coding-style]標籤上? – InternetAussie

+3

這可能是一個標誌,你可以把它分解成更小的函數。 –

+0

我不想重構更小的函數,因爲我在問題中更新了。 – athos

回答

1

這是在某種情況下,一個很好的做法,如果你不能分割功能爲多個較小的功能,但你必須知道,當一個局部變量超出範圍的調用析構函數可能會或可能不一個問題,例如,如果你想是這樣的:

#include <iostream> 
#include <vector> 
#include <string> 

int main(int argc, const char* argv[]) 
{ 
    using namespace std; 

    vector<string>::const_iterator it; 

    { 
    const vector<string> data = {"foo", "bar", "baz"}; 
    it = data.begin(); 
    } 

    cout << *it << endl; 

    return 0; 
} 

,你在這兒一個const_iterator存儲時的範圍被關閉,所以你得到了一個未定義行爲,被釋放的vector。這並不意味着你的解決方案不是一個好的解決方案,它只是意味着你必須考慮到任何具體的缺點。

這也是好的,如果你需要在一個函數的多個部分分配較多的資源,這樣就可以分配和逐步釋放他們,而不需要記憶秒殺。

+0

很好的提醒要被警惕! – athos