分享
 
 
 

Effective C++: Item 21

王朝vc·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

依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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有