Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are many other subtle points surrounding const correctness in C++. I suppose the question here has simply been about C, but I'll give some related examples since the tag is C++ :</p> <ul> <li><p>You often pass large arguments like strings as <code>TYPE const &amp;</code> which prevents the object from being either modified or copied. Example :</p> <p><code>TYPE&amp; TYPE::operator=(const TYPE &amp;rhs) { ... return *this; }</code></p> <p>But <code>TYPE &amp; const</code> is meaningless because references are always const.</p></li> <li><p>You should always label class methods that do not modify the class as <code>const</code>, otherwise you cannot call the method from a <code>TYPE const &amp;</code> reference. Example :</p> <p><code>bool TYPE::operator==(const TYPE &amp;rhs) const { ... }</code></p></li> <li><p>There are common situations where both the return value and the method should be const. Example :</p> <p><code>const TYPE TYPE::operator+(const TYPE &amp;rhs) const { ... }</code></p> <p>In fact, const methods must not return internal class data as a reference-to-non-const.</p></li> <li><p>As a result, one must often create both a const and a non-const method using const overloading. For example, if you define <code>T const&amp; operator[] (unsigned i) const;</code>, then you'll probably also want the non-const version given by :</p> <p><code>inline T&amp; operator[] (unsigned i) { return const_cast&lt;char&amp;&gt;( static_cast&lt;const TYPE&amp;&gt;(*this)[](i) ); }</code></p></li> </ul> <p>Afaik, there are no const functions in C, non-member functions cannot themselves be const in C++, const methods might have side effects, and the compiler cannot use const functions to avoid duplicate function calls. In fact, even a simple <code>int const &amp;</code> reference might witness the value to which it refers be changed elsewhere.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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