【问题标题】:Strange strings behaviour when const referenceconst 引用时奇怪的字符串行为
【发布时间】: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 &amp;,我就不会再遇到这个问题了

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

【问题讨论】:

  • 你引用了一个在调用 test 之前就死掉的临时对象。

标签: c++ c++11


【解决方案1】:

str_ 是对临时对象的引用。当您在构造函数的主体中使用str_ 时,临时对象仍然存在。当您在test 中使用str_ 时,临时不再存在。

你的程序有未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2012-10-20
    相关资源
    最近更新 更多