Main BLOGGER
Google
WWW THIS BLOG
Thursday, July 21, 2005
 
C++ const
From http://www.cs.duke.edu/csed/cplus/const/
1. Pass by Const Reference to combine efficiency and safety.
void foo(int const ¶m)
The pass-by-reference (indicated by the & in the parameter) means that no copy is made in passing an argument. The const modifier means that the parameter cannot be modified within the body of foo. The reference is for efficiency and the const is for safety.
Note:
The C++ standard requires a const-modified reference parameter for literal/temporary arguments; a reference parameter without the const modifier won't support literal/constant arguments

2. Const Member function

char operator[ ]( int k ) const; // for const strings
char & operator[ ]( int k ); // for non-const strings

The string indexing functions would then be rewritten as:

char operator[ ](const string & self, int k ); // for const strings
char & operator[ ](string & self, int k ); // for non-const strings

string s="abc";
print(s[1]); //const string
s[1]='d'; //non-const string

3. Mutable data
class List
{
private:
mutable Node *myCurrentPtr;
public:
void next() const;
};

void List::next() const {
myCurrentPtr = myCurrentPtr->next;
}

A mutable data member can be modified by a const function.

Programming with const can be painful. It's easy to miss the appearance of const in compiler error messages --- be sure that you look for it when you get a "member function foo not implemented" error. You'll also get the function signature/prototype --- look for const to see if you put a const in the header file, for example, but forgot to add the const when defining the function.



<< Home

Powered by Blogger

Google
WWW THIS BLOG