On 11/20/2012 03:57 PM, Matthew Gillen wrote:
On 11/20/2012 03:41 PM, Greg London wrote:
Why would I need "const" when I pass by reference, but not need const
when
I pass by value?

Because references are not pointers, and you cannot "re-seat" the
reference.
   http://www.parashift.com/c++-faq/reseating-refs.html

If you want the nitty-gritty details on how references are implemented:
  http://www.parashift.com/c++-faq/overview-refs.html

Sorry, I jumped the gun. Your problem had nothing to do with re-seating a reference.

The problem in your example:
 ...
 Note("hello world\n");
 ...
 void Note( string &msg){ ...

is that "hello world", by virtue of being a string literal, *is* a const string, but your function prototype (when sans-const) is indicating that the function reserves the right to modify the string.

When you pass by value, you're always getting a copy, so the effect is essentially:
 Note(new std::string("hello world\n");

...and there's never a problem modifying your local copy of the original string. However, if you pass by reference, you're not making a new copy, so if the source object has some restrictions (e.g. is const), then you can't pass it to functions that reserve the right to modify it.

Const-correctness can be tricky when you're first learning it, but if you get it right it is a great tool to make the the compiler help you.

Matt
_______________________________________________
Hardwarehacking mailing list
[email protected]
http://lists.blu.org/mailman/listinfo/hardwarehacking

Reply via email to