📄 ec4.htm
字号:
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. One of 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. (See Item M19, however, for a discussion of how const parameters can lead to the creation of temporary 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 objectcout << s[0]; // fine reading a // non-const Strings[0] = 'x'; // fine writing a // non-const Stringconst String cs = "World"; // const String objectcout << cs[0]; // fine reading a // const Stringcs[0] = 'x'; // error! writing a // const StringBy 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); ... operator char *() const { return data;}private: char *data;};const String s = "Hello"; // declare constant objectchar *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 clients. For example, your String class might want to cache the length of the object whenever it's requested (see Item M18): class String {public: // the constructor makes data point to a copy // of what value points to String(const char *value): lengthIsValid(false) { ... } ... size_t length() const;private: char *data; size_t dataLength; // last calculated length // of string bool lengthIsValid; // whether length is // currently valid};size_t 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 aboveprivate: char *data; mutable size_t dataLength; // these data members are // now mutable; they may be mutable bool lengthIsValid; // modified anywhere, even // inside const member}; // functionssize_t String::length() const{ if (!lengthIsValid) { dataLength = strlen(data); // now fine
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -