FAQ 14.13 Can an object legally be changed even though there is a const reference (pointer) to it?

FAQ 14.13 Can an object legally be changed even though there is a const reference (pointer) to it?

graphics/new_icon.gif

Yes, due to aliasing.

The const part restricts the reference (pointer); it does not restrict the object. Many programmers erroneously think that the object on the other end of a const reference (pointer) cannot change. For example, if const int& i refers to the same int as int& j, j can change the int even though i cannot. This is called aliasing, and it can confuse programmers who are unaware of it.

 #include <iostream> using namespace std; void sample(const int& i, int& j) throw() {   int orig = i;   j++;                                               <-- 1   if (i != orig)     cout << "The value of i is different!\n"; } int main() {   int x = 3;   sample(x, x); } 

(1) Incrementing j can change the int called i

There is no rule in C++ that prohibits this sort of thing. In fact, it is considered a feature of the language that programmers can have several pointers or references refer to the same object (plus it could not be figured out in some cases, e.g., if there are intermediate functions between main() and sample(const int&,int&) and if these functions are defined in different source files and are compiled on different days of the week). The fact that one of those references or pointers is restricted from changing the underlying object is a restriction on the reference (or pointer), not on the object.



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