c ++ 11:在VS2015中为带有Initializer_list的全局STL“ map <string,string =“”>”分配崩溃

时间:2018-07-19 16:48:09

标签: 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;
}

2 个答案:

答案 0 :(得分:6)

代码崩溃,因为您正在初始化server { listen 80; server_name hello.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/vertical/academy; } location / { include proxy_params; #proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/vertical/academy/academy.sock; } } ,其值为std::string的{​​{1}}。

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

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

'\0'

答案 1 :(得分:0)

已更改:

{ "char",      '\0' },

收件人:

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

今天早上眼睛很棘手...