No, you have to mark your function as not modifying the argument:
void Note(const string &msg) { ...
Most functions I've written in C++ have had const parameters.
Now, if you want the function to modify the parameter, but only a local
copy of the parameter, then you should pass by value (i.e. omit the '&'
and the 'const')
Matt
On 11/20/2012 04:15 PM, Greg London wrote:
So, if I have a subroutine that passes by reference,
and I want to pass in something that can't be modified,
I have to put it into some intermediate variable first?
That seems.... inefficient.
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
_______________________________________________
Hardwarehacking mailing list
[email protected]
http://lists.blu.org/mailman/listinfo/hardwarehacking