In C ++, ifstream does not use new, and delete is not used up.
C ++ started from C #, and many things do not understand. The following code is used:
# Include
# Include
Int main (){
Using namespace std;
Ifstream file;
Basic_ifstream Wfile;
Char c;
// Open and close with a basic_filebuf
File. rdbuf ()-> open ("basic_filebuf_close.txt", ios: in );
File> c;
Cout <c <endl;
File. rdbuf ()-> close ();
// Open/close directly
File. open ("iotest.txt ");
File> c;
Cout <c <endl;
File. close ();
// Open a file with a wide character name
Wfile. open (L "iotest.txt ");
// Open and close a nonexistent with a basic_filebuf
File. rdbuf ()-> open ("ziotest.txt", ios: in );
Cout <file. fail () <endl;
File. rdbuf ()-> close ();
// Open/close directly
File. open ("ziotest.txt ");
Cout <file. fail () <endl;
File. close ();
}
Below is my chat record with Daniel. (It feels great to have a great guy help answer your questions !)
Skyline wolf 9:35:42 have two questions
Ifstream file;
File. open ("iotest.txt ");
File. close ();
1. Can I call the file method without a new one?
2. After the operation is complete, call file. close () and do not use delete. Why?
Daniel 9:33:55
Think about it. What is new?
Skyline wolf 9:35:42
New is used to create objects and allocate memory space on the stack. Do you mean this ifstream is a template, so you don't need it?
9:36:22
Daniel 9:36:22
New. This object is declared on the stack.
Skyline wolf 9:38:19
You mean that if an object is only known on the front, the variable will be allocated to the stack. If it is known, it will be allocated to the stack with new. Is that true?
9:38:40
Daniel 9:38:40
Yes
Daniel 9:39:09
Objects on the stack do not need to be deleted.
Skyline wolf 9:39:15
Oh, the second question is clear. The first question is still incomprehensible,
Skyline wolf 9:39:37
The objects on the stack do not need to be deleted. I know it.
Skyline wolf 9:40:16
Oh, does C ++ use the default constructor?
Skyline wolf 9:40:38
This object was initialized before the call.
9:41:46
Daniel 9:41:46
Yes
You can set a breakpoint in the constructor to observe it.
Skyline wolf 9:43:01
3Q, clear. Well, this debugging method is quite good.