vendredi 31 mars 2017

Strange strings behaviour when const reference

I encountered a strange behaviour with const reference strings when it goes over 15 characters. It simply replaces the beginning of the string by null bytes.

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();
}

This is happening only with strings exceeding 15 characters. If a remove the const & in the attribute of the class, I don't have this problem anymore I've experienced in an other project memory leaks in my code when strings were exceeding 15 characters, so I wonder :

What is really happening when a string goes over 15 characters ?

Aucun commentaire:

Enregistrer un commentaire