Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass references by value in C++?
    text
    copied!<p>I'm trying to create am immutable type (class) in C++,</p> <p>I made it so that all methods "aka member functions" don't modify the object and return a new instance instead.</p> <p>I'm running across a bunch of issues, but they all revolve around the reference types in C++.</p> <p>One example is when passing parameters of the same class type by reference:</p> <pre><code>Imm Imm::someOp( const Imm&amp; p_im ) const { ... p_im = p_im.someOtherOp(); //error, p_im is const, can't modify it! ... } </code></pre> <p>The error is caused by passing the value by reference. If instead, I was passing the reference by value, then the error line above would not be an error! </p> <p>Consider a Java/C# example</p> <pre><code>class Imm { ... Imm someOp( Imm p_im ) { .... p_im = p_im.someOtherOp(); //ok, you're not modifying the //original object, just changing the local reference .... } .... } </code></pre> <p>How can I do something like this in C++? I know I can use pointers but then I run into the whole memory management mess. I don't want to worry about who owns references to objects. </p> <p>Ideally I'd like to design the class to be like immutable strings in python; you can use them without ever noticing or even knowing that they're immutable, and they just behave as you expect; they just work.</p> <p><strong>EDIT</strong></p> <p>Of course I can get around it by passing-by-value or by using a temp variable (which is what I'm doing currently). What I'm asking about is "how to pass references by value in C++"</p> <p>I'm expecting the answer to revolve around something in the STL, I'm currently looking into smart_ptr family of templates.</p> <p><strong>UPDATE</strong></p> <p>Thanks for the responses, I realize there's no escape from pointers. (see my <a href="https://stackoverflow.com/questions/653211/stl-class-for-reference-counted-pointers">other question</a>, which is really a follow up on this one)</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