0

Is cout ever copied implicitly?

For example, is the cout object passed to the second overloaded operator in the code below, and the cout object inside its implementation are the same objects or is one a copy of cout?

My understanding is that the first implementation is correct because the << operator works for any ostream object, e.g. it will work for ofstream objects for writing to files.

//First implementation
ostream& operator<<(ostream& os, const Date& dt)
{
    os << dt.mo << '/' << dt.da << '/' << dt.yr;
    return os;
}

//Second implementation
ostream& operator<<(ostream& os, const Date& dt)
{
    cout << dt.mo << '/' << dt.da << '/' << dt.yr;
    return cout;
}

//using second implementation on object date
cout<<date;
Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
Krypt
  • 55
  • 4

2 Answers2

3

Your example doesn't copy any ostream, you use references everywhere. If you look at std::cout you can see that it is noncopyable (here and here)

David
  • 27,652
  • 18
  • 89
  • 138
1

std::istream and std::ostream objects cannot be copied. Since std::cout is an ostream object (its type is derived from std::ostream), it cannot be copied.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165