【发布时间】:2017-04-01 01:36:22
【问题描述】:
当 const 引用字符串超过 15 个字符时,我遇到了一个奇怪的行为。它只是用空字节替换字符串的开头。
Class A
{
public:
A(const std::string& str) : str_(str)
{
std::cout << str_ << std::endl;
}
void test()
{
std::cout << str_ << std::endl;
}
private:
const std::string& str;
};
int main()
{
//printing the full string "01234567890123456789"
A a("01234567890123456789");
//replacing first bytes by '\0', printing "890123456789"
a.test();
}
只有超过 15 个字符的字符串才会出现这种情况。如果在类的属性中删除const &,我就不会再遇到这个问题了
当一个字符串超过 15 个字符时,到底发生了什么?
【问题讨论】:
-
你引用了一个在调用
test之前就死掉的临时对象。