+ 13
Does it make sense to use only references?
From earlier discussions here I remember that using references makes sense when the arguments become large, to reduce the copy cost (memory and speed). For smaller arguments like char, int, double, bool etc., the size of a pointer may be larger or equal to the size of the value to be copied, so it's not really bringing an advantage to use pointers/references unless we insist on changing the value in place. Now I am reading a book where the author, without further comments, uses const refs almost exclusively, even for the smallest types. Are there valid reasons to do that?
8 ответов
+ 6
Mh well if you pass by value you create a copy so changing one won't change the other. I explained it badly, here's an example of what I had in mind:
struct Foo {
const int& bar;
Foo(const int& baz) : bar(baz) { }
};
int main(){
int baz = 4;
Foo foo(baz);
baz = 5;
cout << foo.bar;
}
But yeah, why. ¯\_(ツ)_/¯ This might even get into trouble if `baz` runs out of scope.
Maybe it's just a habit the author picked up, because it probably doesn't matter a lot of the time. But it seems silly to pass primitive types by ref if you don't need to.
+ 11
I mean since it's a reference you can still change the value you're passing as const& from the outside, so that might be half a usecase, but I don't really see how that's actually useful most of the time.
Not sure why you'd ever pass a bool as a const reference to be honest. Not only because of size but it's another useless layer of indirection aswell.
+ 6
If it's just about being able to change a value on the outside, couldn't you pass by value and make it const?
(Probably not that useful either.)
+ 5
Schindlabua, ah okay I see.
So meticulously every pathway is const-closed except the outermost one; so you can change the value of an object *only* from the outside?
That's like inverted privacy! Or rather slavery? 😂
Is there a use case for something like that?
+ 5
I haven't looked at these things yet, but I think I get the idea.
+ 4
If you put it like that, I think I found an example that's not too out there, I guess you could call it "signalling":
https://code.sololearn.com/ciF9q06qMId4/?ref=app
But yeah that's an edge case at best.
+ 4
The tl;dr is that there are two threads running at the same time and the main thread wants to signal the other one when to stop. The other thread shouldn't change the "stop sign" itself, so you pass in a const reference that can only be changed from the outside.
0
I mean since it's a reference you can still change the value you're passing as const& from the outside, so that might be half a usecase, but I don't really see how that's actually useful most of the time.