Reputation: 1103
In this program:
#include<iostream>
#include<fstream>
int main()
{
std::ofstream ob;
ob<<"hello"<<std::endl;
return 0;
}
Where is this hello
written/outputted since ob
is not associated with any file? Is it the internal file buffer?
Upvotes: 1
Views: 47
Reputation: 2214
The output is ignored.
When anything is written to a stream, it calls the overflow
method (or an internal equivalent) of its associated streambuf for each character written. As per cppreference.com for std::basic_filebuf
:
If the associated file is not open (
is_open() == false
), returnsTraits::eof()
before doing anything.
As soon as overflow
returns an eof
, the stream's failbit
is set and all other output is ignored.
Upvotes: 2
Reputation: 15521
The std::ofstream class template has several constructors. This example uses the std::ofstream default constructor to construct an object that is not associated to a file.
Excerpt from the reference:
1) Default constructor: constructs a stream that is not associated with a file: default-constructs the std::basic_filebuf and constructs the base with the pointer to this default-constructed
std::basic_filebuf
member.
@Spencer's answer details what happens then.
Upvotes: 1