Effective C++: Item 21

类别:VC语言 点击:0 评论:0 推荐:
依myan文章中的网址,找到了些资料,故而贴出来,以方便大家! Item 21: Use const whenever possible.The wonderful thing about const is that it allows you to specify a certain semantic constraint -- a particular object should not be modified -- and compilers will enforce that constraint. It allows you to communicate to both compilers and other programmers that a value should remain invariant. Whenever that is true, you should be sure to say so explicitly, because that way you enlist your compilers' aid in making sure the constraint isn't violated.

The const keyword is remarkably versatile. Outside of classes, you can use it for global or namespace constants (see Item 1) and for static objects (local to a file or a block). Inside classes, you can use it for both static and nonstatic data members (see also Item 12).

For pointers, you can specify whether the pointer itself is const, the data it points to is const, both, or neither:

char *p = "Hello"; // non-const pointer, // non-const data const char *p = "Hello"; // non-const pointer, // const data char * const p = "Hello"; // const pointer, // non-const data const char * const p = "Hello"; // const pointer, // const data This syntax isn't quite as capricious as it looks. Basically, you mentally draw a vertical line through the asterisk of a pointer declaration, and if the word const appears to the left of the line, what's pointed to is constant; if the word const appears to the right of the line, the pointer itself is constant; if const appears on both sides of the line, both are constant.

When what's pointed to is constant, some programmers list const before the type name. Others list it after the type name but before the asterisk. As a result, the following functions take the same parameter type:

class Widget { ... }; void f1(const Widget *pw); // f1 takes a pointer to a // constant Widget object void f2(Widget const *pw); // so does f2 Because both forms exist in real code, you should accustom yourself to both of them.

Some of the most powerful uses of const stem from its application to function declarations. Within a function declaration, const can refer to the function's return value, to individual parameters, and, for member functions, to the function as a whole.

Having a function return a constant value often makes it possible to reduce the incidence of client errors without giving up safety or efficiency. In fact, as Item 29 demonstrates, using const with a return value can make it possible to improve the safety and efficiency of a function that would otherwise be problematic.

For example, consider the declaration of the operator* function for rational numbers that is introduced in Item 19:

const Rational operator*(const Rational& lhs, const Rational& rhs); Many programmers squint when they first see this. Why should the result of operator* be a const object? Because if it weren't, clients would be able to commit atrocities like this:

Rational a, b, c; ... (a * b) = c; // assign to the product // of a*b! I don't know why any programmer would want to make an assignment to the product of two numbers, but I do know this: it would be flat-out illegal if a, b, and c were of a built-in type. Oneof the hallmarks of good user-defined types is that they avoid gratuitous behavioral incompatibilities with the built-ins, and allowing assignments to the product of two numbers seems pretty gratuitous to me. Declaring operator*'s return value const prevents it, and that's why It's The Right Thing To Do.

There's nothing particularly new about const parameters -- they act just like local const objects. Member functions that are const, however, are a different story.

The purpose of const member functions, of course, is to specify which member functions may be invoked on const objects. Many people overlook the fact that member functions differing only in their constness can be overloaded, however, and this is an important feature of C++. Consider the String class once again:

class String { public: ... // operator[] for non-const objects char& operator[](int position) { return data[position]; } // operator[] for const objects const char& operator[](int position) const { return data[position]; } private: char *data; }; String s1 = "Hello"; cout << s1[0]; // calls non-const // String::operator[] const String s2 = "World"; cout << s2[0]; // calls const // String::operator[] By overloading operator[] and giving the different versions different return values, you are able to have const and non-const Strings handled differently:

String s = "Hello"; // non-const String object cout << s[0]; // fine -- reading a // non-const String s[0] = 'x'; // fine -- writing a // non-const String const String cs = "World"; // const String object cout << cs[0]; // fine -- reading a // const String cs[0] = 'x'; // error! -- writing a // const String By the way, note that the error here has only to do with the return value of the operator[] that is called; the calls to operator[] themselves are all fine. The error arises out of an attempt to make an assignment to a const char&, because that's the return value from the const version of operator[].

Also note that the return type of the non-const operator[] must be a reference to a char -- a char itself will not do. If operator[] did return a simple char, statements like this wouldn't compile:

s[0] = 'x'; That's because it's never legal to modify the return value of a function that returns a built-in type. Even if it were legal, the fact that C++ returns objects by value (see Item 22) would mean that a copy of s.data[0] would be modified, not s.data[0] itself, and that's not the behavior you want, anyway.

Let's take a brief time-out for philosophy. What exactly does it mean for a member function to be const? There are two prevailing notions: bitwise constness and conceptual constness.

The bitwise const camp believes that a member function is const if and only if it doesn't modify any of the object's data members (excluding those that are static), i.e., if it doesn't modify any of the bits inside the object. The nice thing about bitwise constness is that it's easy to detect violations: compilers just look for assignments to data members. In fact, bitwise constness is C++'s definition of constness, and a const member function isn't allowed to modify any of the data members of the object on which it is invoked.

Unfortunately, many member functions that don't act very const pass the bitwise test. In particular, a member function that modifies what a pointer points to frequently doesn't act const. But if only the pointer is in the object, the function is bitwise const, and compilers won't complain. That can lead to counterintuitive behavior:

class String { public: // the constructor makes data point to a copy // of what value points to String(const char *value = 0); operator char *() const { return data;} private: char *data; }; const String s = "Hello"; // declare constant object char *nasty = s; // calls op char*() const *nasty = 'M'; // modifies s.data[0] cout << s; // writes "Mello" Surely there is something wrong when you create a constant object with a particular value and you invoke only const member functions on it, yet you are still able to change its value! (For a more detailed discussion of this example, see Item 29.)

This leads to the notion of conceptual constness. Adherents to this philosophy argue that a const member function might modify some of the bits in the object on which it's invoked, but only in ways that are undetectable by a client. For example, your String class might want to cache the length of the object whenever it's requested:

class String { public: // the constructor makes data point to a copy // of what value points to String(const char *value = 0): lengthIsValid(0) { ... } unsigned int length() const; private: char *data; unsigned int dataLength; // last calculated length // of string bool lengthIsValid; // whether length is // currently valid }; unsigned int String::length() const { if (!lengthIsValid) { dataLength = strlen(data); // error! lengthIsValid = true; // error! } return dataLength; } This implementation of length is certainly not bitwise const -- both dataLength and lengthIsValid may be modified -- yet it seems as though it should be valid for const String objects. Compilers, you will find, respectfully disagree; they insist on bitwise constness. What to do?

The solution is simple: take advantage of the const-related wiggle room the C++ standardization committee thoughtfully provided for just these types of situations. That wiggle room takes the form of the keyword mutable. When applied to nonstatic data members, mutable frees those members from the constraints of bitwise constness:

class String { public: ... // same as above private: char *data; mutable unsigned int dataLength; // these data members are // now mutable; they may be mutable bool lengthIsValid; // modified anywhere, even // inside const member }; // functions unsigned int String::length() const { if (!lengthIsValid) { dataLength = strlen(data); // now fine lengthIsValid = true; // also fine } return dataLength; } mutable is a wonderful solution to the bitwise-constness-is-not-quite-what-I-had-in-mind problem, but it was added to C++ relatively late in the standardization process, so your compilers may not support it yet. If that's the case, you must descend into the dark recesses of C++, where life is cheap and constness may be cast away.

Inside a member function of class C, the this pointer behaves as if it had been declared as follows:

C * const this; // for non-const member // functions const C * const this; // for const member // functions That being the case, all you have to do to make the problematic version of String::length (i.e., the one you could fix with mutable if your compilers supported it) valid for both const and non-const objects is to change the type of this from const C * const to C * const. You can't do that directly, but you can fake it by initializing a local pointer to point to the same object as this does. Then you can access the members you want to modify through the local pointer:

unsigned int String::length() const { // make a local version of this that's // not a pointer-to-const String * const localThis = const_cast<String * const>(this); if (!lengthIsValid) { localThis->dataLength = strlen(data); localThis->lengthIsValid = true; } return dataLength; } Pretty this ain't, but sometimes a programmer's just gotta do what a programmer's gotta do.

Unless, of course, it's not guaranteed to work, and sometimes the old cast-away-constness trick isn't. In particular, if the object this points to is truly const, i.e., was declared const at its point of definition, the results of casting away its constness are undefined. If you want to cast away constness in one of your member functions, you'd best be sure that the object you're doing the casting on wasn't originally defined to be const.

There is one other time when casting away constness may be both useful and safe. That's when you have a const object you want to pass to a function taking a non-const parameter, and you know the parameter won't be modified inside the function. The second condition is important, because it is always safe to cast away the constness of an object that will only be read -- not written -- even if that object was originally defined to be const.

For example, some libraries have been known to incorrectly declare the strlen function as follows:

int strlen(char *s); Certainly strlen isn't going to modify what s points to -- at least not the strlen I grew up with. Because of this declaration, however, it would be invalid to call it on pointers of type const char *. To get around the problem, you can safely cast away the constness of such pointers when you pass them to strlen:

const char *klingonGreeting = "nuqneH"; // "nuqneH" is // "Hello" in // Klingon size_t length = strlen(const_cast<char*>(klingonGreeting)); Don't get cavalier about this, though. It is guaranteed to work only if the function being called, strlen in this case, doesn't try to modify what its parameter points to.

本文地址:http://com.8s8s.com/it/it3443.htm