我收到了用户报告我开发的库中的段错误的错误报告.
错误代码的最小示例是:
#include <map>
#include <string>
#include <iostream>
void f(std::map<std::string, std::string> m = {})
{
std::cout << m.size() << "\n";
for (const auto& s: m) {
std::cout << s.first << "->" << s.second <<"\n";
}
}
int main()
{
f();
}
Run Code Online (Sandbox Code Playgroud)
当使用GCC编译时(我测试了4.8.2和4.7.3),它正确地打印0
为容器的大小,但是循环内部的段错误(根本不应该执行).
不过,我可以修复通过改变声明的问题:
void f(std::map<std::string, std::string> m = std::map<std::string, std::string>{})
Run Code Online (Sandbox Code Playgroud)
复制map
作品:
void f(std::map<std::string, std::string> mx = {})
{
auto m = mx;
std::cout << m.size() << "\n";
for (const auto& s: m) …
Run Code Online (Sandbox Code Playgroud) 在尝试使用clang-3.4(从git编译)时,它无法编译我的一个项目,抱怨在解决重载运算符时出现歧义.我发现有两个模板化运算符,其中一个被声明为成员函数,另一个被称为非成员函数,它们似乎都是同样好的匹配.
继SSCCE之后展示了这种情况:
#include <iostream>
struct ostr {
std::ostream& s;
template<class T>
ostr& operator<<(const T& x) { s << x; return *this; }
};
struct xy {
double x, y;
};
template<class Stream>
Stream& operator<<(Stream& s, const xy& x) {
s << "[" << x.x << ", " << x.y << "]";
return s;
}
int main() {
ostr os{std::cout};
xy x{4, 5};
os << "Value is: " << x <<"\n";
}
Run Code Online (Sandbox Code Playgroud)
该项目之前编译很好,我再次检查这个SSCCE几个编译器(gcc 4.5
,4.6
,4.7
,4.8 …