8.6.2. Nonconstant Pointer to Constant Data

A nonconstant pointer to constant data is a pointer that can be modified to point to any data item of the appropriate type, but the data to which it points cannot be modified through that pointer. Such a pointer might be used to receive a built-in array argument to a function that should be allowed to read the elements, but not modify them. Any attempt to modify the data in the function results in a compilation error. The declaration for such a pointer places const to the left of the pointer’s type, as in

 const int *countPtr;

The declaration is read from right to left as “countPtr is a pointer to an integer constant” or more precisely, “countPtr is a non-constant pointer to an integer constant.

Figure 8.10 demonstrates GNU C++’s compilation error message produced when attempting to compile a function that receives a nonconstant pointer to constant data, then tries to use that pointer to modify the data.

When a function is called with a built-in array as an argument, its contents are effectively passed by reference because the built-in array’s name is implicitly convertible to the address of the built-in array’s first element. However, by default, objects such as arrays and vectors are passed by value—a copy of the entire object is passed. This requires the execution-time overhead of making a copy of each data item in the object and storing it on the function call stack. When a pointer to an object is passed, only a copy of the address of the object must be made—the object itself is not copied.


Image Performance Tip 8.1

If they do not need to be modified by the called function, pass large objects using pointers to constant data or references to constant data, to obtain the performance benefits of pass-by-reference and avoid the copy overhead of pass-by-value.



Image Software Engineering Observation 8.3

Passing large objects using pointers to constant data, or references to constant data offers the security of pass-by-value.



Image Software Engineering Observation 8.4

Use pass-by-value to pass fundamental-type arguments (e.g., ints, doubles, etc.) to a function unless the caller explicitly requires that the called function be able to directly modify the value in the caller. This is another example of the principle of least privilege.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.50