Notes 1 of More Effective C++ —— Basics

来源:互联网 发布:淘宝6s特价1380能买吗 编辑:程序博客网 时间:2024/06/13 23:14

Item 1: Pointers Versus References

     1. There is no such thing as a null reference, a reference must always refer to some object.

     2. C++ requires references to be initialized, while pointers are subject to no such restriction, Pointer need to test agian NULL when used

           string& rs = s ;// initialize

           string *ps;

            if(ps)  {    };  // test the pointer

    3. Reference can't be reassigned, it always refer to the object with which it is initialized.

           string & rs  =  s1;   

           string *ps = &s1;

           rs = s2;   // rs still refer to s1, but s1's value is changed to value of s2

           ps = &s2;  //ps now points to s2, s1 kept unchanged


Item 2: C++ style casts

      1.  static_cast:   like the cast in C-style cast, can't use it to do constness cast.

                 static_cast<double>(frstnumber)/secondnumber;

       2. const_cast   cast away the constness or volatileness of an expression

           class SpecialWidget:;

           void update(SpecialWidget *psw)

          const SpecialWidget sw;

          update(const_cast<SpecialWidget*>(&sw))


      3. dynamic_cast:  perform safe casts down or across a inheritance hierarchy


Item 3: Never treat arrays polymorphically

        class BST { ...   };

        class BalancedBST: public BST ( ...   );

        void printBSTArray()

        {

              for( int i=0; i<numlements; i++)

             {   s<< array[i]   }//distance between array[0] and array[i] is i*sizeof(BST)

        }

       if you use like this:

              BalanceBST bSTArray[10];

              printBSTArray(count, bBSTArray, 10)  //size should be i*sizeof(BalancedBST), different from the definitionb

0 0
原创粉丝点击