[英]C++ Operator+ string long produces Segmentation Fault
The following code produces a segmentation fault with only the xxx line printed (ie before the "pre concat"). 以下代码会产生仅显示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();
}
Any idea why? 知道为什么吗?
(I will just use a method, overloading operators on standard types is probably a bad idea as it is likely to conflict with other modules. But damned if I can see what is wrong with this.) (我将只使用一种方法,在标准类型上重载运算符可能不是一个好主意,因为它很可能与其他模块发生冲突。但是,如果我看到这有什么问题,该死的。)
"MyKey"
is not std::string
. "MyKey"
不是std::string
。 It's const char[6]
. 它是
const char[6]
。 And for "MyKey" + ((long long) timev)
, your overloading operator won't be called. 对于
"MyKey" + ((long long) timev)
,不会调用您的重载运算符。 Instead, "MyKey"
will decay to const char*
, then "MyKey" + ((long long) timev)
might get out of the bound of the array, which is UB . 相反,
"MyKey"
将衰减为const char*
,然后"MyKey" + ((long long) timev)
可能会超出数组UB的范围 。
The code is equivalent as: 该代码等效为:
const char* key = "MyKey";
string cname = key + ((long long) timev); // or key[((long long) timev)]
You could 你可以
string cname = string("MyKey") + ((long long) timev);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.