2010-06-29 55 views
2
//s_request_view() constructor is declared as below 
namespace Identity_VIEW 
{ 
Published_view_identity s_request_view("SAMPLE"); 
}; 

//The constructor is called in another source file as below, 
bind_view(Identity_VIEW::s_request_view); 

這個代碼在windows上工作正常,但在SBC(PowerPC)上s_request_view作爲NULL傳遞。爲什麼全局變量沒有用字符串初始化我在extern中給出的變量

任何人都可以請幫我找出爲什麼它的行爲不同?

+0

我們可以看到Published_view_identity及其構造函數的屬性 – Mark 2010-06-29 04:44:13

+1

另外,bind_view被「普通」代碼或另一個全局構造函數? – 2010-06-29 04:48:27

+1

不知何故,我敢打賭,在另一個全球構造函數。 – 2010-06-29 06:38:39

回答

6

我想,這裏的答案是,編譯器不保證全局變量初始化的順序。如果你的bind_view是從另一個全局變量的構造函數中調用的 - 你將會有一個浮動錯誤。

嘗試使用以下方法:

namespace Identity_VIEW 
{ 
    Published_view_identity & getRequestView() 
    { 
     static Published_view_identity s_request_view ("Sample"); 
     return s_request_view; 
    } 
} 

... 
bind_view(Identity_VIEW::getRequestView()); 

,可以幫助解決全局變量初始化的順序。然而,這種解決方案不是線程安全的(如果你在乎)...

+1

+1用於顯示更安全的訪問初始化類方法,然後超出了s_request_view的初始化討論線程安全問題。 – stinky472 2010-06-29 07:29:26

相關問題