Note that there are some explanatory texts on larger screens.

plurals
  1. POwould it ever make sense to modify a reference to a const char* passed in as a parameter to a method?
    text
    copied!<p>Say I have something along the lines of:</p> <pre><code>int main() { const char* someString = "Hello"; MyClass myClass; myClass.modifySomeString(someString); return 0; } </code></pre> <p>And two possible method signatures for <code>modifySomeString</code>:</p> <p><strong>case A</strong> <code>void MyClass::modifySomeString(const char* inBuffer)</code></p> <p>This seems straight-out pointless since I'd be getting a value so whatever I do with inBuffer does not affect the original someString in <code>main()</code>, right?</p> <p><strong>case B</strong> <code>void MyClass::modifySomeString(const char*&amp; inBuffer)</code></p> <p>Here, I have a reference to the pointer so potentially I could actually modify the original "string" in main() (and probably should call the parameter inOutBuffer for clarity...). But besides the fact that I could cast to remove the const and modify the actual parameter inside my method... wouldn't this be just a bad thing to do? </p> <p>I mean:</p> <ol> <li>someString was declared const in main to start with, so trying to pass it to a method for it to modify it is nonsensical</li> <li>inside the method, if I'm stating the parameter is const too, again it just seems wrong to then try and go around its const to modify it affecting someString in main.</li> </ol> <p>Am I right about my observations on both cases A and B? Or is there a reason where it might be reasonable to pass a const string to a method and expect the method to still modify the original?</p> <p>Personally, I think if I'm passing a const to the method, the method should instead have an out parameter where I get a new string without changing the original one. Something like:</p> <pre><code>void MyClass::modifySomeString(const char* inBuffer, char*&amp; outBuffer) </code></pre> <p>But I'm interested in suggestions or someone explaining why it's perfectly fine to modify the const parameter.</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