【问题标题】:Is this a compiler bug? Am I doing something wrong?这是编译器错误吗?难道我做错了什么?
【发布时间】:2023-03-13 04:31:01
【问题描述】:

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

#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 值变成了垃圾。 但我看不出有什么理由不能以这种方式创建地图。

这是 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

【问题讨论】:

  • 您必须将CString 对象显式转换为LPCTSTR。不过最好一起远离CString
  • @Chad,连同所有省略号的上个世纪废话:D
  • 我已更新我的代码以进行显式转换。但是,同样的问题仍然存在。
  • 放弃那个,2015年才试过。
  • 您编辑的代码在 vs2013 中适用于我(除非删除 stdafxatlstr,并将 _tmain(...) 替换为 main())。 32 位和 64 位...

标签: c++ dictionary compiler-bug


【解决方案1】:

我已将您的示例复制到 MSVC 中。它甚至不仅仅是错误的打印 - 它是 ATL CString 破坏地图时的内存违规。但一切都适用于 std::string。结论 - 错误的 ATL 实现。如果我要大胆猜测,我会说,这是移动构造函数中的一个错误。

【讨论】:

  • 更新了我的代码以使用 printf,并进行了显式转换以证明该错误仍然存​​在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-13
  • 1970-01-01
  • 2019-08-16
相关资源
最近更新 更多