【发布时间】:2021-11-08 12:57:47
【问题描述】:
当我使用基于范围的 for 循环遍历临时 std::string(右值?)时,似乎有一个额外的字符,即空终止符 \0。
当字符串不是临时的(而不是左值?)时,没有多余的字符。为什么?
std::map<char, int> m;
for (char c : "bar") m[c] = 0;
for (auto [c, f] : m) {
if (c == '\0') std::cout << "this is a null char, backward slash zero" << std::endl;
std::cout << c << std::endl;
}
输出:
this is a null char, backward slash zero
a
b
r
(注意空行,\0 正在打印)
相比:
std::map<char,int> m;
std::string s = "bar";
for (char c : s) m[c] = 0;
for (auto [c, f] : m) {
if (c == '\0') std::cout << "this is a null char, backward slash zero" << std::endl;
std::cout << c << std::endl;
}
输出:
a
b
r
【问题讨论】: