c++ - 这是编译器错误吗?难道我做错了什么?

标签 c++ dictionary compiler-bug

我正在尝试制作一个简单的 map 来查找一些数据,但结果却很奇怪:

#include "stdafx.h"
#include "atlstr.h"
#include <map>

enum InputTypes { Manual, Automatic, Assisted, Imported, Offline };

struct Params
{
    int inputType;
    const char* moduleName;
    DWORD flag;
};

int _tmain()
{
    std::map<CString, Params> options {
        { "Add",       { Manual,    "RecordLib",  0 } },
        { "Open",      { Assisted,  "ViewLib",    1 } },
        { "Close",     { Imported,  "EditLib",    2 } },
        { "Inventory", { Automatic, "ControlLib", 3 } },
        { "Report",    { Offline,   "ReportLib",  4 } }
    };

    for (std::map<CString, Params>::iterator iter = options.begin(); iter != options.end(); ++iter)
    {
        printf("Entry: %s ==> { %d, %s, %d }\n", (const char*)(iter->first),
            iter->second.inputType, iter->second.moduleName, iter->second.flag);
    }


    return 0;
}

输出:

Entry: îþîþîþîþîþîþîþîþîþîþîþîþ[â0; t ==> { 0, RecordLib, 0 }
Entry: Close ==> { 3, EditLib, 2 }
Entry: Inventory ==> { 1, ControlLib, 3 }
Entry: îþîþîþîþîþîþîþîþîþîþîþîþCâ0# t ==> { 2, ViewLib, 1 }
Entry: Report ==> { 4, ReportLib, 4 }

如您所见,一些 CString 值变成了垃圾。 但我看不出有任何理由无法以这种方式创建 map 。

这是 Microsoft Visual Studio 2013 编译器中的错误吗?
我的代码是否缺少某些特殊之处?

############编辑##############

对于那些认为这是 CString 问题的人,我用 std::string 重写了它,得到了更糟糕的输出:

#include "stdafx.h"
#include "atlstr.h"
#include <map>

enum InputTypes { Manual, Automatic, Assisted, Imported, Offline };

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

int _tmain(int argc, _TCHAR* argv[])
{
    std::map<std::string, Params> options{
        { "Add",       { Manual, "RecordLib", 0 } },
        { "Open",      { Assisted, "ViewLib", 1 } },
        { "Close",     { Imported, "EditLib", 2 } },
        { "Inventory", { Automatic, "ControlLib", 3 } },
        { "Report",    { Offline, "ReportLib", 4 } }
    };

    for (std::map<std::string, Params>::iterator iter = options.begin(); iter != options.end(); ++iter)
    {
        printf("Entry: %s ==> { %d, %s, %d }\n", iter->first.c_str(),
            iter->second.inputType, iter->second.moduleName.c_str(), iter->second.flag);
    }
    return 0;
}

输出

Entry:  ==> { 0, , 0 }
Entry: Report ==> { 4, , 4 }

请注意,这确实适用于 IDEOne

最佳答案

我已将您的示例复制到 MSVC 中。它甚至不仅仅是不正确的打印 - 它是 ATL CString 中销毁映射时的内存违规。但都适用于 std::string。结论 - 有缺陷的 ATL 实现。如果我大胆猜测,我会说,这是移动构造函数中的错误。

关于c++ - 这是编译器错误吗?难道我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33549613/

相关文章:

C++ 预处理器标准行为

c++ - 如何使用 std::map 获取双向迭代器的索引?

c++ - 定义转换构造函数和转换运算符时哪个优先,为什么编译器会对此转换有所不同?

dictionary - 如何在 dc.geoChoroplethChart 中添加缩放效果?

c++ - throw 或 delete 表达式可以依赖吗?

c++ - 当 C++ 从函数的返回值将元素存储到 std::vector 时出现意外结果

c++ - 如何确保WSASend()会发送数据?

c++ - 内联函数静态常量是否唯一?

python - 在 cassandra DB 中插入字典

python - 在 Python 中使用字典进行财务跟踪