FAQ 14.02 How can C programmers avoid making unexpected changes to objects?

FAQ 14.02 How can C++ programmers avoid making unexpected changes to objects?

With proper use of the keyword const, the C++ compiler detects many unexpected changes to objects and flags these violations with error messages at compile time. This is often called const correctness. For example, function f() uses the const keyword to restrict itself so that it won't be able to change the caller's string object:

 #include <string> using namespace std; void f(const string& s) throw();  // Parameter is received                                   // by reference-to-const 

If f() changes its passed string anyway, the compiler flags it as an error at compile time:

 void f(const string& s) throw() {   #ifdef GENERATE_ERROR     s += "foo";                                      <-- 1   #endif } 

(1) Error: The string cannot be mutated via s

In contrast, function g() declares its intent to change the caller's string object by its lack of the const keyword in the appropriate place:

 void g(string& s) throw();  // Parameter is received by                             //  reference-to-non-const 

For example, it is legal and appropriate for g() to modify the caller's string object:

 void g(string& s) throw() {   s += "foo";  // OK: Modifies the caller's string object } 

Also it would be legal and appropriate for g() to pass its parameter to f(), since the called function, f(), is at least as restrictive as the caller, g() (in this case, the called function is actually more restrictive):

 void g(string& s) throw() {   f(s);        // OK (though it doesn't happen to modify                // caller's string object)   s += "foo";  // OK: Modifies the caller's string object } 

However, it would be illegal for the opposite to occur. That is, if f() passed its parameter to g(), the compiler would give an error message since the called function, g(), is less restrictive than the caller, f():

 void f(const string& s) throw() {   #ifdef GENERATE_ERROR     g(s);                                            <-- 1   #endif } 

(1) Error: The const string& cannot be passed as a string&



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net