2015-11-05 79 views
4

我問了一個earlier question,它在CString和Unicode問題中脫離了主題。
我現在將示例縮小爲namespace stdcout(而不是printf)。
但核心問題依然存在。使用初始值列表與std :: map

這與question nominated as a duplicate有關,但是是分開的。 這個問題是關於maps-in-map的,並且已經超過2年了,注意這個問題是編譯器團隊的一個優先事項。 (顯然,這是不是一個優先事項)
這個問題是值得現在用的初始值設定正確我保持開放

的?
有沒有簡單的方法可以解決這個問題,而沒有一個主要的解決方法?
(這是基於一個更復雜的程序小例子)

#include <map> 
#include <string> 
#include <iostream> 

struct Params 
{ 
    int   inputType; 
    std::string moduleName; 
}; 

int main() 
{ 
    std::map<std::string, Params> options{ 
     { "Add",  { 30, "RecordLib" } }, 
     { "Open",  { 40, "ViewLib" } }, 
     { "Close",  { 50, "EditLib" } }, 
     { "Inventory", { 60, "ControlLib"} }, 
     { "Report", { 70, "ReportLib" } } 
    }; 

    for (const auto& pair : options) 
    { 
     std::cout << "Entry: " << pair.first << " ==> { " << pair.second.moduleName << " }" << std::endl; 
    } 

    return 0; 
} 

輸出

Entry: ==> { } 
Entry: Report ==> { } 

你只能看到最終的字符串"Report"存活。

它真的在我看來像std::map的初始化列表剛剛壞了。

我正在使用帶有Unicode的Microsoft Visual Studio 2013。
這發生在兩個DebugRelease建立,與Optimizations Disabled/O2 相同的代碼工作正常上IDEOne

+0

你可以添加你有什麼編譯選項,即優化級別,debug/nodebug等 – Slava

+0

我相信這仍然是過於複雜。它與'std :: map '一起工作嗎?用'std :: map '? – Lol4t0

+0

這個錯誤不會發生在'map '上。該bug的關鍵部分是將鍵值映射到其中包含字符串的結構。 – abelenky

回答

2

Slava的堅持下,我與構建函數一起尋找一個簡單的辦法:

#include <map> 
#include <string> 
#include <iostream> 

struct Params 
{ 
    int   inputType; 
    std::string moduleName; 
    Params(const int n, const std::string& s) : 
     inputType(n), 
     moduleName(s) 
    { } 
}; 

int main() 
{ 
    std::map<std::string, Params> options = { 
     { "Add",  Params(30, "RecordLib") }, 
     { "Open",  Params(40, "ViewLib" ) }, 
     { "Close",  Params(50, "EditLib" ) }, 
     { "Inventory", Params(60, "ControlLib") }, 
     { "Report", Params(70, "ReportLib") } 
    }; 

    for (const auto& pair : options) 
    { 
     std::cout << "Entry: " << pair.first << " ==> { " << pair.second.moduleName << " }" << std::endl; 
    } 

    return 0; 
} 

但是,原始代碼應該已經工作,並且顯然是Microsoft公認的錯誤。

+0

好(不幸)解決方法。 – mskfisher

相關問題