![]() |
On const reference arguments passing
Hi,
I am trying to change my way of programming (I am still learning) , in particular I am putting an effort in passing const ref to functions, when possible. When possible means (to me) when that function is not going to modify the object I pass to it. Many times though, I create an object, call a function (taking a non- const ref) that modifies it somehow and then need to use that object as parameter for a function that takes a const ref, that will only read the object. The compiler complains, since I am passing a non-const object to the function and the only thing that I can do is to cast away the constness, but is this the right way to go? It feels wrong... Thanks for your hints. /G |
Re: On const reference arguments passing
On 16 Apr, 16:12, "Giff" <Giffn...@gmail.com> wrote:
Forget my post. |
Re: On const reference arguments passing
Giff wrote:
> I am trying to change my way of programming (I am still learning) , in > particular I am putting an effort in passing const ref to functions, > when possible. > > When possible means (to me) when that function is not going to modify > the object I pass to it. That's a good rule. Also, when you think of treading the object as "a value", it may still be reasonable to pass by reference to const, instead of passing by value. > Many times though, I create an object, call a function (taking a non- > const ref) that modifies it somehow and then > need to use that object as parameter for a function that takes a const > ref, that will only read the object. That sounds reasonable. > The compiler complains, since I am passing a non-const object to the > function and the only thing that I can do is to cast away the > constness, but is this the right way to go? It feels wrong... That doesn't sound right. Could you please support this statement with code? I can only see such behaviour of the compiler if the situation is reversed -- calling a function expecting a ref to non- const object from a function where the object is const (i.e. you passed the object by reference to const): class a {}; void foo(a& ra); void bar(a const & ra) { foo(ra); // error } int main() { a object; bar(object); } V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask |
Re: On const reference arguments passing
On 16 Apr, 16:27, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
> > The compiler complains, since I am passing a non-const object to the > > function and the only thing that I can do is to cast away the > > constness, but is this the right way to go? It feels wrong... > > That doesn't sound right. I know, sorry for the post. I was doing something else wrong and I have just been too impatient. My apologies to the group, and thanks for your reply anyway. |
| All times are GMT. The time now is 02:40 PM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.