0

I accidently tried to stream a QString with std::ostream. However, compilation (Windows SDK 7.1) succeeded, but put a warning:

Warning:C4717: 'operator<<' : recursive on all control paths, function will cause runtime stack overflow

Finally, I'm wondering why the recursion arises. Here is a small piece of code to reproduce. Note: Without the overloaded constructor, the compiler raises the expected error (no operator found which takes a right-hand operand of type 'QString').

#include <iostream>
#include <QString>

class CTest
{
  public:
    CTest(QString str) {}
    friend std::ostream & operator <<(std::ostream & out, const CTest & cTest)
    {
      out << "std::string";
      out << QString("HelloWorld");

      return out;
    }
};

int main(int argc, char *argv[])
{ 
  CTest t("testing");
  std::cout << t;

  return 0;
}
braggPeaks
  • 1,158
  • 10
  • 23

1 Answers1

0

Since QString doesn't have operator << defined, line

out << QString("HelloWorld");

is implicitly converted to

out << CTest(QString("HelloWorld"));

(closest overload, due to constructor CTest(QString str)), which calls operator << recursively for CTest infinite amount of times.

Ilya Kobelevskiy
  • 5,245
  • 4
  • 24
  • 41