最近在玩C++, 前幾天在玩C++ STL
今天找了effective & more effective C++兩本書來看
這兩本書很早就塞在我的硬碟了,只是以前一直看不懂
現在總算可以從裡面讀出點趣味來了
// show stack and heap
// malloc and new 的差別在於 malloc只是單純的allocate記憶體但沒有call constructor!
#include
//#define PI 3.1415926 avoid this
//item 11
//write your own versions of the copy constructor and the assignment operator if you have any pointers in your class.
//當你的class有pointer ,而你使用預設的assign or copy operator你很可能會造成memory leak的error, 某個obj可能delete某個memory, 在你不知覺情況下
using namespace std;
//item 1
const double PI = 3.14;
class test {
public:
//item 9 最好提供一個空的constructor ! , 否則在多載建構子時, 若直接使用new 會發生錯誤
test()
{
this -> myNumber = "000";
}
test( char* P )
{
this->myNumber = P;
}
//item 1
static const double PI = 3.1415926; //save space!
// item 1 more flexible
friend ostream& operator<<( ostream& a, test& b);
//item 6
~test()
{
delete myNumber;
}
int magic;
private:
char* myNumber;
};
ostream& operator<<( ostream& a, test& b )
{
a << b.myNumber;
return a; // << << << <<
}
int main()
{
//item 2
test* me = new test( "0910883869" );
cout << *me << endl;
//item 3
test* p = ( test* ) malloc( sizeof( test ) * 10 ); // no construct .. gabarge?
test* p2 = new test[ 10 ]; // shound use this, call the constructor for each objs in ary
delete [] p2; // shound use the, call the destructor for each objs in ary
free( p );
//item 5, avoid using typedef for arys!
string *str1 = new string();
string *str2 = new string[100];
delete str1;
str1 = 0;
//use delete [] str1 causes error!
delete [] str2;
str2 = 0;
//item 7 out of memory condition , 很深入的探討記憶體不足的問題(例外處理), 當要alocate大量記憶體時,值得借鏡
try {
p = new test[1000];
} catch( std::bad_alloc &p) {
cout << "out of memory";
// 實際上不知道在哪時發生的,但記憶體已經分配到空間了
}
return 0;
}
2007年11月13日 星期二
more effective c++
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言