以下代码产生了一个段错误,只打印了 xxx 行(即在“pre concat”之前)。
cerr << "xxx + " << ((long long) timev);
string cname = "MyKey" + ((long long) timev);
string operator+(const string& str, long long nr) {
cerr << "Pre concat "; // << str << "$" << nr;
stringstream ss;
ss << str << nr;
cerr << "Post concat";
return ss.str();
}
知道为什么吗?
(我将只使用一种方法,在标准类型上重载运算符可能不是一个好主意,因为它可能会与其他模块发生冲突。但该死的,如果我能看出这有什么问题。)
最佳答案
"MyKey"
不是 std::string
。它是 const char[6]
。对于 "MyKey"+ ((long long) timev)
,您的重载运算符将不会被调用。相反,"MyKey"
将衰减为 const char*
,然后 "MyKey"+ ((long long) timev)
可能会退出数组的边界,即 UB .
代码等同于:
const char* key = "MyKey";
string cname = key + ((long long) timev); // or key[((long long) timev)]
你可以
string cname = string("MyKey") + ((long long) timev);
关于C++ Operator+ string long 产生 Segmentation Fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36245980/