c++11:在 VS2015 中使用 initializer_list 分配全局 STL "map<string, string>"崩溃

标签 c++ c++11

<分区>

有人知道为什么这段代码在“ map ”行崩溃并显示错误消息:“调试断言失败:无效的空点”吗?

#include <cstdint>
#include <map>
#include <string>

using namespace std;

map<string, string> VarZeroTable = {
    { "bool",      "false" },
    { "int",       "0" },
    { "char",      '\0' },
    { "float",     "0.0"},
    { "double",    "0.0"},
    { "string",    "\"\"" },
    { "short",     "0" },
    { "long",      "0" },
    { "uint64_t",  "0" },
    { "uint32_t",  "0" },
    { "uint16_t",  "0" },
    { "uint8_t",   "0" },
    { "uintmax_t", "0" },
    { "int8_t",    "0" },
    { "int16_t",   "0" },
    { "int32_t",   "0" },
    { "int64_t",   "0" },
    { "intptr_t",  "nullptr" },
    { "uintptr_t", "uintptr_t" },
    { "size_t",    "0" },
    { "ptrdiff_t", "0"}
};

int main(int argc, char** argv) {
    int count = VarZeroTable.count("int64_t");
    return 0;
}

最佳答案

代码崩溃是因为您正在使用值为 '\0'char 初始化 std::string

因为 std::string 没有采用单个 char 的构造函数,最接近的匹配构造函数显然是采用 const char 的构造函数* 指针。由于 '\0' 是值为 0(null)的文字,null 最终被传递给指针参数,并在初始化期间崩溃。

您可以通过为该 std::string 使用初始化列表来强制创建其中包含单个字符的字符串:

// ...
{ "char",      { '\0' } },
// ...

关于c++11:在 VS2015 中使用 initializer_list 分配全局 STL "map<string, string>"崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51428043/

相关文章:

c++ - 为什么不能使用 constexpr 全局变量来初始化 constexpr 引用类型?

c++ - 如何将 byte[] 放入 capnp::Data

c++ - 在 API 设计中,什么时候我应该更喜欢长度为 2 的 std::tuple 而不是一对?

c++ - MFC : accessing CMainFrame's CImageList from ChildView

c++ - 如何让 CMake 在构建之前运行 python 脚本,以便为我的项目生成要在构建中使用的文件?

C++ double 和舍入

c++ - 只有两个 parent 之一的赋值运算符

c++ - 如何在 C++ 中模拟模板化的 std::function

C++ std::bind 重新绑定(bind)函数

c++ - 在构造函数中使用临时参数作为默认参数