2014-02-06 54 views
1

ALL,不同的編譯結果:Mac vs Windows

我正在研究涉及STL及其跨平臺的大量使用的項目。在Windows上,我使用的是MSVC 2010 Pro,在Mac上,我在Snow Leopard的頂部安裝了XCode 4.2。

我的代碼看起來是這樣的:

m_sort.m_type.size() == 0 ? m_sort.m_type.push_back(SortObject(SORT_BY_NAME, true)) : m_sort.m_type.insert(it - 1, SortObject(SORT_BY_NAME, true)); 

其中m_sort.m_type是標準::矢量<>將被用於排序另一個的std ::矢量<>。

Visual Studio編譯好這段代碼:沒有警告,沒有錯誤。 但是,試圖編譯上了XCode這個代碼我得到這個錯誤:

Left operand to ? is void, but right operand is of type 'iterator' (aka '__normal_iterator')

是否有解決Mac上的錯誤一個簡單的方法? 爲什麼此代碼在Windows上成功構建? 或者,也許它在STL實現XCode for SL與MSVC在Windows上的區別?

謝謝。

+2

解決這個問題的最簡單方法可能是明確的if分支。 (我假設三元運算符的要點是用一個表達式來計算其中一個表達式,但不是另一個,這不是正確的方式) – Xarn

+0

如果這種情況發生*是相關的 - 這可能是XCode默認情況下不使用'libC++'標準庫實現 - 我知道你沒有使用Boost,但如果這有助於看看http://stackoverflow.com/a/20615086/368896 –

+0

@Xarn,我打算表現明智嗎?還有「?」保存源代碼行。 ;-) – Igor

回答

1

因此,作爲已經發布弗拉德,問題是,三元表達不能有類型? void : T組合,除非void-type表達式是一個throw表達式。

這可以解決或者通過

1)鑄造的第二操作數的給void返回類型,這基本上意味着,我們只關心的副作用發生的和我們實際上並沒有從表達式返回

2)將給定的三元表達式轉換爲if/else分支。我個人非常喜歡選項2,因爲它減少了閱讀者的認知負荷(並且允許更多的空間來解釋評論),並且沒有表現的懲罰。

注意,有幾個在使用if/else語句也有超過三元運算性能損失的情況下,但只能在低優化設置,其中的代碼編譯器看起來像這樣:

if (is_ham){ 
    taste = 1; 
} else { 
    taste = 0; 
} 

發出分支執行路徑,而不是條件移動。但是,在較高的優化設置(O2,O3)中,此代碼應該發出與此相同的指令。

taste = (is_ham)? 1 : 0; 

還要注意,用於與副作用的表達式,必須有一個分支執行路徑無論哪種方式和所討論的表達式僅僅是副作用。

2

寫下面的方式

m_sort.m_type.size() == 0 ? 
    m_sort.m_type.push_back(SortObject(SORT_BY_NAME, true)) : 
    (void)m_sort.m_type.insert(it - 1, SortObject(SORT_BY_NAME, true)); 

從C++標準

2 If either the second or the third operand has type void, one of the following shall hold: — The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (15.1); the result is of the type and value category of the other.

— Both the second and the third operands have type void; the result is of type void and is a prvalue. [ Note: This includes the case where both operands are throw-expressions. —end note ]