JavaScript is required to for searching.
Skip Navigation Links
Exit Print View
Oracle Solaris Studio 12.3: C++ User's Guide     Oracle Solaris Studio 12.3 Information Library
search filter icon
search icon

Document Information

Preface

Part I C++ Compiler

1.  The C++ Compiler

2.  Using the C++ Compiler

3.  Using the C++ Compiler Options

Part II Writing C++ Programs

4.  Language Extensions

5.  Program Organization

6.  Creating and Using Templates

7.  Compiling Templates

8.  Exception Handling

9.  Improving Program Performance

9.1 Avoiding Temporary Objects

9.2 Using Inline Functions

9.3 Using Default Operators

9.4 Using Value Classes

9.4.1 Choosing to Pass Classes Directly

9.4.2 Passing Classes Directly on Various Processors

9.5 Cache Member Variables

10.  Building Multithreaded Programs

Part III Libraries

11.  Using Libraries

12.  Using the C++ Standard Library

13.  Using the Classic iostream Library

14.  Building Libraries

Part IV Appendixes

A.  C++ Compiler Options

B.  Pragmas

Glossary

Index

9.5 Cache Member Variables

Accessing member variables is a common operation in C++ member functions.

The compiler must often load member variables from memory through the this pointer. Because values are being loaded through a pointer, the compiler sometimes cannot determine when a second load must be performed or whether the value loaded before is still valid. In these cases, the compiler must choose the safe, but slow, approach and reload the member variable each time it is accessed.

You can avoid unnecessary memory reloads by explicitly caching the values of member variables in local variables, as follows:

This optimization is most productive when the values can reside in registers, as is the case with primitive types. The optimization may also be productive for memory-based values because the reduced aliasing gives the compiler more opportunity to optimize.

This optimization may be counter productive if the member variable is often passed by reference, either explicitly or implicitly.

On occasion, the desired semantics of a class requires explicit caching of member variables, for instance when there is a potential alias between the current object and one of the member function’s arguments. For example:

complex& operator*= (complex& left, complex& right)
{
  left.real = left.real * right.real + left.imag * right.imag;
  left.imag = left.real * right.imag + left.image * right.real;
}

will yield unintended results when called with:

x*=x;