常量引用时奇怪的字符串行为

Strange strings behaviour when const reference

本文关键字:字符串 引用 常量      更新时间:2023-10-16

当 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 '', printing "890123456789"
  a.test();
}

只有超过 15 个字符的字符串才会发生这种情况。如果删除类属性中的const &,我不再有这个问题 我在字符串超过 15 个字符时在其他项目中遇到过代码中的内存泄漏,所以我想知道:

当字符串超过 15 个字符时,到底发生了什么?

str_是对临时对象的引用。在构造函数的主体中使用 str_ 时,临时仍处于活动状态。当您在test中使用str_时,临时不再有效。

程序具有未定义的行为。