Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>const</code> is about program semantics and not about implementation details. You should mark a member function <code>const</code> when it does not change the visible state of the object, and should be callable on an object that is itself <code>const</code>. Within a <code>const</code> member function on a class <code>X</code>, the type of <code>this</code> is <code>X const *</code>: pointer to constant <code>X</code> object. Thus all member variables are effectively <code>const</code> within that member function (except <code>mutable</code> ones). If you have a <code>const</code> object, you can only call <code>const</code> member functions on it.</p> <p>You can use <code>mutable</code> to indicate that a member variable may change even within a <code>const</code> member function. This is typically used to identify variables used for caching results, or for variables that don't affect the actual observable state such as mutexes (you still need to lock the mutex in the <code>const</code> member functions) or use counters.</p> <pre><code>class X { int data; mutable boost::mutex m; public: void set_data(int i) { boost::lock_guard&lt;boost::mutex&gt; lk(m); data=i; } int get_data() const // we want to be able to get the data on a const object { boost::lock_guard&lt;boost::mutex&gt; lk(m); // this requires m to be non-const return data; } }; </code></pre> <p>If you hold the data by pointer rather than directly (including smart pointers such as <code>std::auto_ptr</code> or <code>boost::shared_ptr</code>) then the pointer becomes <code>const</code> in a <code>const</code> member function, but not the pointed-to data, so you can modify the pointed-to data.</p> <p>As for caching: in general the compiler cannot do this because the state might change between calls (especially in my multi-threaded example with the mutex). However, if the definition is inline then the compiler can pull the code into the calling function and optimize what it can see there. This might result in the function <em>effectively</em> only being called once.</p> <p>The next version of the <a href="http://www.open-std.org/jtc1/sc22/wg21/" rel="noreferrer">C++ Standard (C++0x)</a> will have a new keyword <code>constexpr</code>. Functions tagged <code>constexpr</code> return a constant value, so the results can be cached. There are limits on what you can do in such a function (in order that the compiler can verify this fact).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload