Valgrind 和 ostream 运算符

Valgrind and ostream operator

为什么 Valgrind 在此代码中显示错误?

//  const char * constructor
String::String(const char* s) {
  size = 0;
  while(s[size] != '[=10=]')
    ++size;
  capacity = 0;
  str = new char[size];
  for (int i = 0; i < size; ++i) {
    str[i] = s[i];
    if (size > capacity && capacity == 0) {
      ++capacity;
    } else if ((size > capacity && capacity != 0)) {
      capacity *= 2;
    }
  }
}

// overloading the ostream operator
std::ostream &operator<<(std::ostream &os, const String& other) {
  return std::operator<<(os, other.str);
}

// testing
TEST(Iostream, Out) {
  std::stringstream os;
  String s = "lol";
  os << s;
  ASSERT_EQ(os.str(), "lol");
}

// main function for testing
int main() {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

/////////////////////////////////////////// /////////////////// 如果我没有在任何地方使用它,为什么 strlen 会显示在这里?

==11274== Invalid read of size 1
==11274==    at 0x48425F4: strlen (vg_replace_strmem.c:469)
==11274==    by 0x49BCBCD: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)

Why is strlen showing here if I haven't used it anywhere?

return std::operator<<(os, other.str);

这与您执行以下操作时调用的函数相同:

void foo(std::ostream& stream, const char * ptr) {
  stream << ptr;
}

如果不是通过 strlen() 或类似的东西,流应该如何知道传递的以 null 结尾的字符串的长度?