Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to deal with initialization of non-const reference member in const object?
    primarykey
    data
    text
    <p>Let's say you have a class</p> <pre><code> class C { int * i; public: C(int * v):i(v) {}; void method() const; //this method does not change i void method(); //this method changes i } </code></pre> <p>Now you may want to define const instance of this class</p> <pre><code> const int * k = whatever; const C c1(k); //this will fail </code></pre> <p>but this will fail because of non-const int C's constructor C(int * v)</p> <p>so you define a const int constructor</p> <pre><code> C(const int * v):i(v) {}; //this will fail also </code></pre> <p>But this will fail also since C's member "int * i" is non-const.</p> <p>What to do in such cases? Use mutable? Casting? Prepare const version of class?</p> <p>edit: After discussion with Pavel (below) I investigated this problem a bit. To me what C++ does is not correct. Pointer target should be a strict type, that means that you could not for example do the following:</p> <pre><code>int i; const int * ptr; ptr = &amp; i; </code></pre> <p>In this case language grammar treats <code>const</code> as a promise not to change pointer's target. In addition <code>int * const ptr</code> is a promise not to change pointer value itself. Thus you have two places where const can be applied. Then you may want your class to model a pointer (why not). And here things are falling into pieces. C++ grammar provides const methods which are able to promise not to change field's values itself but there is no grammar to point out that your method will not change targets of your in-class pointers. </p> <p>A workaround is to define two classes <code>const_C</code> and <code>C</code> for example. It isn't a royal road however. With templates, their partial specializations it's hard not to stuck into a mess. Also all possible arguments variations like <code>const const_C &amp; arg</code>, <code>const C &amp; arg</code>, <code>const_C &amp; arg</code>, <code>C &amp; arg</code> don't look pretty. I really don't know what to do. Use separate classes or const_casts, each way seems to be wrong.</p> <p>In both cases should I mark methods which don't modify pointer's target as const? Or just follow traditional path that const method doesn't change object's state itself (const method don't care about pointer target). Then in my case all methods would be const, because class is modelling a pointer thus pointer itself is <code>T * const</code>. But clearly some of them modify pointer's target and others do not.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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