用户登录  |  用户注册
首 页商业源码原创产品编程论坛
当前位置:PB创新网文章中心编程技巧编程其他

More Efffective C++ Item 1

减小字体 增大字体 作者:佚名  来源:本站整理  发布时间:2009-03-16 19:35:44

More Effective C++ 翻?g?]??著者同意,翻?g及原文?H供?W??交流使用

Item 1:指????引用的?^?e
    指????引用看起?碛泻艽??^?e(指??用"*"和"->"操作符,引用用"."操作符),
但是它??似乎做相似的事情.指??和引用都??你?g接指向其它?ο?.然而,你真的能
?Q定何?r使用其中一??而不是另外一???
    首先,?????J?R到?]有一??空引用.一??引用必????是指向某一?ο?.?Y果,如果
你有一????量它的目的指向另一?ο?,但是有可能?]有一???ο笥??碇赶?,你????使
????量成?橹羔?,因?槟憧梢灾盟??榭?.另外一方面,如果??量必????是指向一???ο?,
也就是,如果你的?O??不允?S一????量?榭?,你或?S????使??量?橐?用.
    "但是,",你想知道,“象下面又有怎?拥拿孛??"
         char *pc = 0;    //?O指???榭?
         char& rc = *pc //使引用指向
                                //空指??
    唔,?@可是麻?┑?,完全的并且易受?_的.?Y果是不?_定的(???g器能?a生??出?碜?
它喜?g做的任何事情),任何???@?N代?a的人????避免掉除非他??同意?K止?@?幼?.如果
你??心在你的??件存在?@?N事,你最好完全避免使用引用,或者挑?x一??更好的程序?T??
工作.因此我??可以忽略引用是"空"的可能性.
    因?橐?用必??指向一???ο?,所以C++要求引用必??初始化:
        string& rs         //?e?`,引用必??
                               //被初始化
        string s("xyzzy");
        string& rs = s;    //正?_,rs指向s
    指??就?]有?@?N限制:
        string *ps         //?]有初始化的指??:
                              //正?_但是冒?U
    ?]有一??空引用的事??意味著使用引用比使用指??更有效.那是因?樵谑褂靡???
引用之前?]有必要?y??它的有效性:
        void printDouble(const double& rd)
        {
           cout<<rd;               //不需要?y??rd,它
        }                             //必定指向一??double
    相反,指??一般?f??????被?y??以防它?榭?:
        void printDouble(const double *pd)
        {
          if (pd) {
            cout << *pd;            //??空指??作?z?y
          }           
        }

    指??和引用另外一??重要的不同是指??可以可以重新分配以指向不同的?ο?.
然而引用??是指向它初始化指向的?ο?:
        string s1("Nancy");
        string S2("Clancy");

        string& rs = s1;          //rs指向s1
 
        string *ps = &s1;       //ps指向s1
    
        rs = s2;                    //rs仍然指向s1
                                      //但是s1的值?F在
                                      //????"Clancy"

        ps = &s2                 //ps?F在指向s2:
                                     //但是是s1?]有改??
    一般而言,你????使用指???o??何?r你必??考?]到有存在空指向的可能性(在?@
?N情?r下你可以?O指???榭?)或者你需要能?蛟诓煌?的?r?g指向不同的?ο?(在?@?N
情?r下你可以改??指??所指的?ο?).你????使用引用?o??何?r你????知道??是要有
一???ο笾赶?,同?r你也????知道,一旦你指向一???ο?,你?⒃僖膊荒苤赶蛉魏纹渌?
?ο?.
    有另外一?N情?r你????使用引用,那就是??你???F某些操作符?r.最普通的例子
是操作符[].遮?w操作符典型的需要返回能?蜃??槲?派目?说哪澄?:
       vector<int> v(10);          //??建一??大小??10的整型向量:
                                    //向量是?俗?C++?熘械哪0?
                                    //(?? Item 35)
      
       v[5] = 10;                  //委派目?耸?
                  //操作符[]的返回值

     如果操作符[]返回一??指??,最后一句?Z句?????@????:
        *v[5] = 10;
    
     但是?@?⑹?v看起?硐笠???指??向量,然而它?s不是.因?檫@??理由,你差不多
??是需要操作符[]返回一??引用.(?τ谠????t的一??有趣的例外,??看Item 30).
   
     ?x?褚?用的重要?l件是??你知道你有某物要指向,??你永?h不需要指向任何其
它的?ο?,??你需要???F操作符,它的?Z?x要求充分考?]到指??的令人不快的特性.
任何其它情?r,???Q使用指??.
Original English:
Item 1:  Distinguish between pointers and references. ? Item M1, P1

Pointers and references look different enough (pointers use the "*" and
"->" operators, references use "."), but they seem to do similar things.
Both pointers and references let you refer to other objects indirectly.
How, then, do you decide when to use one and not the other? ? Item M1, P2

First, recognize that there is no such thing as a null reference. A reference
must always refer to some object. As a result, if you have a variable whose
purpose is to refer to another object, but it is possible that there might
not be an object to refer to, you should make the variable a pointer, because
then you can set it to null. On the other hand, if the variable must always
refer to an object, i.e., if your design does not allow for the possibility
that the variable is null, you should probably make the variable a reference.
 ? Item M1, P3

"But wait," you wonder, "what about underhandedness like this?" ? Item M1, P4

char *pc = 0;          // set pointer to null

char& rc = *pc;        // make reference refer to
                       // dereferenced null pointer
Well, this is evil, pure and simple. The results are undefined (compilers can
generate output to do anything they like), and people who write this kind of
code should be shunned until they agree to cease and desist. If you have to
worry about things like this in your software, you're probably best off avoiding
references entirely. Either that or finding a better class of programmers to
work with. We'll henceforth ignore the possibility that a reference can be "null."
? Item M1, P5

Because a reference must refer to an object, C++ requires that references
be initialized: ? Item M1, P6

string& rs;             // error! References must
                        // be initialized

string s("xyzzy");

string& rs = s;         // okay, rs refers to s
Pointers are subject to no such restriction: ? Item M1, P7

string *ps;             // uninitialized pointer:
                        // valid but risky
The fact that there is no such thing as a null reference implies that it can
be more efficient to use references than to use pointers. That's because
there's no need to test the validity of a reference before using it: ?
Item M1, P8

void printDouble(const double& rd)
{
    cout << rd;         // no need to test rd; it
}                       // must refer to a double
Pointers, on the other hand, should generally be tested against null: ?
Item M1, P9

void printDouble(const double *pd)
{
  if (pd) {             // check for null pointer
    cout << *pd;
  }
}
Another important difference between pointers and references is that
pointers may be reassigned to refer to different objects. A reference,
however, always refers to the object with which it is initialized: ?
Item M1, P10

string s1("Nancy");
string s2("Clancy");

string& rs = s1;         // rs refers to s1

string *ps = &s1;        // ps points to s1

rs = s2;                 // rs still refers to s1,
                         // but s1's value is now
                         // "Clancy"

ps = &s2;                // ps now points to s2;
                         // s1 is unchanged
In general, you should use a pointer whenever you need to take into
account the possibility that there's nothing to refer to (in which
case you can set the pointer to null) or whenever you need to be able
to refer to different things at different times (in which case you can
change where the pointer points). You should use a reference whenever
you know there will always be an object to refer to and you also know
that once you're referring to that object, you'll never want to refer
to anything else. ? Item M1, P11

There is one other situation in which you should use a reference, and
that's when you're implementing certain operators. The most common
example is operator[]. This operator typically needs to return something
that can be used as the target of an assignment: ? Item M1, P12

vector<int> v(10);       // create an int vector of size 10;
                         // vector is a template in the
                         // standard C++ library (see Item 35)
v[5] = 10;               // the target of this assignment is
                         // the return value of operator[]

If operator[] returned a pointer, this last statement would have to be
written this way: ? Item M1, P13

*v[5] = 10;

But this makes it look like v is a vector of pointers, which it's not.
For this reason, you'll almost always want operator[] to return a
reference. (For an interesting exception to this rule, see Item 30.) ?
Item M1, P14

References, then, are the feature of choice when you know you have
 something to refer to, when you'll never want to refer to anything
else, and when implementing operators whose syntactic requirements
make the use of pointers undesirable. In all other cases,
stick with pointers.


Tags:

作者:佚名

文章评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论
PB创新网ourmis.com】Copyright © 2000-2009 . All Rights Reserved .
页面执行时间:5,906.25000 毫秒
Email:ourmis@126.com QQ:2322888 蜀ICP备05006790号