1. 程式人生 > >C++中為啥ifstream不用new,用完還不用delete

C++中為啥ifstream不用new,用完還不用delete

剛從C#開始轉C++,有很多東西不理解,如下邊這段程式碼:

  #include <fstream>
  #include <iostream>
  
  int main() {
     using namespace std;
     ifstream file;
     basic_ifstream <wchar_t> 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( );
  }

下邊是我跟大牛的聊天記錄,疑問解開。(有個大牛幫解答疑問感覺就是爽啊!)

skyline wolf 2014/8/11 9:35:42 有2個疑問
ifstream file;
file.open( "iotest.txt" );
file.close( );
1.這裡沒有new就可以呼叫file的方法嗎?
2.用完之後,呼叫file.close(),最終不用delete是為什麼?

大牛 2014/8/11 9:33:55
自己再想想。new是幹什麼的

skyline wolf 2014/8/11 9:35:42
new是用來建立物件,在堆上分配記憶體空間的。你的意思是說這個ifstream是模板所以不用嗎?
9:36:22
大牛 2014/8/11 9:36:22
new的理解對。這個物件是在棧上宣告的

skyline wolf 2014/8/11 9:38:19
你的意思是說,如果一個物件在前邊只是聲名了一下,那麼這個聲名的變數就被分配在了棧上。如果聲名的時候用new就分配在堆上。是這樣嗎?
9:38:40
大牛 2014/8/11 9:38:40
是的

大牛 2014/8/11 9:39:09
棧上的物件不用delete。

skyline wolf 2014/8/11 9:39:15
哦,那第二個問題就清楚了。第一個問題還是不解理,

skyline wolf 2014/8/11 9:39:37
棧上的物件不用delete我是知道的

skyline wolf 2014/8/11 9:40:16
哦,是不是C++使用了預設建構函式?

skyline wolf 2014/8/11 9:40:38
在呼叫 前初始化了這個物件
9:41:46
大牛 2014/8/11 9:41:46
是的
你在建構函式裡面設個斷點觀察下

skyline wolf 2014/8/11 9:43:01
3Q,清楚了。嗯,這個除錯方法挺好的。