📄 mc1.htm
字号:
More Effective C++ | Chapter 1: Basics Back to IntroductionContinue to Item 1: Distinguish between pointers and references.BasicsAh, the basics. Pointers, references, casts, arrays, constructors you can't get much more basic than that. All but the simplest C++ programs use most of these features, and many programs use them all.In spite of our familiarity with these parts of the language, sometimes they can still surprise us. This is especially true for programmers making the transition from C to C++, because the concepts behind references, dynamic casts, default constructors, and other non-C features are usually a little murky.This chapter describes the differences between pointers and references and offers guidance on when to use each. It introduces the new C++ syntax for casts and explains why the new casts are superior to the C-style casts they replace. It examines the C notion of arrays and the C++ notion of polymorphism, and it describes why mixing the two is an idea whose time will never come. Finally, it considers the pros and cons of default constructors and suggests ways to work around language restrictions that encourage you to have one when none makes sense.By heeding the advice in the items that follow, you'll make progress toward a worthy goal: producing software that expresses your design intentions clearly and correctly. Back to BasicsContinue to Item 2: Prefer C++-style castsItem 1: Distinguish between pointers and references.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?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."But wait," you wonder, "what about underhandedness like this?" char *pc = 0; // set pointer to nullchar& rc = *pc; // make reference refer to // dereferenced null pointerWell, 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."Because a reference must refer to an object, C++ requires that references be initialized: string& rs; // error! References must // be initializedstring s("xyzzy");string& rs = s; // okay, rs refers to sPointers are subject to no such restriction: string *ps; // uninitialized pointer: // valid but riskyThe 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: void printDouble(const double& rd){ cout << rd; // no need to test rd; it} // must refer to a doublePointers, on the other hand, should generally be tested against null: 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: string s1("Nancy");string s2("Clancy");string& rs = s1; // rs refers to s1string *ps = &s1; // ps points to s1rs = s2; // rs still refers to s1, // but s1's value is now // "Clancy"ps = &s2; // ps now points to s2; // s1 is unchangedIn 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.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: 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: *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.)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. Back to Item 1: Distinguish between pointers and referencesContinue to Item 3: Never treat arrays polymorphicallyItem 2: Prefer C++-style casts.Consider the lowly cast. Nearly as much a programming pariah as the goto, it nonetheless endures, because when worse comes to worst and push comes to shove, casts can be necessary. Casts are especially necessary when worse comes to worst and push comes to shove.Still, C-style casts are not all they might be. For one thing, they're rather crude beasts, letting you cast pretty much any type to pretty much any other type. It would be nice to be able to specify more precisely the purpose of each cast. There is a great difference, for example, between a cast that changes a pointer-to-const-object into a pointer-to-non-const-object (i.e., a cast that changes only the constness of an object) and a cast that changes a pointer-to-base-class-object into a pointer-to-derived-class-object (i.e., a cast that completely changes an object's type). Traditional C-style casts make no such distinctions. (This is hardly a surprise. C-style casts were designed for C, not C++.)A second problem with casts is that they are hard to find. Syntactically, casts consist of little more than a pair of parentheses and an identifier, and parentheses and identifiers are used everywhere in C++. This makes it tough to answer even the most basic cast-related questions, questions like, "Are any casts used in this program?" That's because human readers are likely to overlook casts, and tools like grep cannot distinguish them from non-cast constructs that are syntactically similar.C++ addresses the shortcomings of C-style casts by introducing four new cast operators, static_cast, const_cast, dynamic_cast, and reinterpret_cast. For most purposes, all you need to know about these operators is that what you are accustomed to writing like this, (type) expressionyou should now generally write like this: static_cast<type>(expression)For example, suppose you'd like to cast an int to a double to force an expression involving ints to yield a floating point value. Using C-style casts, you could do it like this: int firstNumber, secondNumber;...double result = ((double)firstNumber)/secondNumber;With the new casts, you'd write it this way: double result = static_cast<double>(firstNumber)/secondNumber;Now there's a cast that's easy to see, both for humans and for programs.static_cast has basically the same power and meaning as the general-purpose C-style cast. It also has the same kind of restrictions. For example, you can't cast a struct into an int or a double into a pointer using static_cast any more than you can with a C-style cast. Furthermore, static_cast can't remove constness from an expression, because another new cast, const_cast, is designed specifically to do that.The other new C++ casts are used for more restricted purposes. const_cast is used to cast away the constness or volatileness of an expression. By using a const_cast, you emphasize (to both humans and compilers) that the only thing you want to change through the cast is the constness or volatileness of something. This meaning is enforced by compilers. If you try to employ const_cast for anything other than modifying the constness or volatileness of an expression, your cast will be rejected. Here are some examples: class Widget { ... };class SpecialWidget: public Widget { ... };void update(SpecialWidget *psw);SpecialWidget sw; // sw is a non-const object,const SpecialWidget& csw = sw; // but csw is a reference to // it as a const object update(&csw); // error! can't pass a const // SpecialWidget* to a function // taking a SpecialWidget* update(const_cast<SpecialWidget*>(&csw)); // fine, the constness of &csw is // explicitly cast away (and // csw and sw may now be // changed inside update) update((SpecialWidget*)&csw); // same as above, but using a // harder-to-recognize C-style cast Widget *pw = new SpecialWidget;update(pw); // error! pw's type is Widget*, but // update takes a SpecialWidget*update(const_cast<SpecialWidget*>(pw)); // error! const_cast can be used only // to affect constness or volatileness, // never to cast down the inheritance // hierarchBy far the most common use of const_cast is to cast away the constness of an object.The second specialized type of cast, dynamic_cast, is used to perform safe casts down or across an inheritance hierarchy. That is, you use dynamic_cast to cast pointers or references to base class objects into pointers or references to derived or sibling base class objects in such a way that you can determine whether the casts succeeded.1 Failed casts are indicated by a null pointer (when casting pointers) or an exception (when casting references): Widget *pw;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -