this post was submitted on 03 May 2024
243 points (94.5% liked)

Programmer Humor

31250 readers
1554 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 4 years ago
MODERATORS
 

Alt text:

Image that says:

HOLY SHIT!! IS THAT A MOTHERF*CKING C++ REFERENCE???

int& a = b;

you are viewing a single comment's thread
view the rest of the comments
[–] TheEntity@lemmy.world 5 points 2 months ago (1 children)

never mind, I looked it up. It’s a “reference” instead of a pointer. Similar, but unlike a pointer it doesn’t create a distinct variable in memory of its own.

I'm almost sure it does create a distinct variable in memory. Internally it's still a pointer, specifically a const pointer (not to be confused with a pointer to a const value; it's the address that does not change). Think about it as a pointer that is only ever dereferenced and never used as a pointer. So yes, like the other commenter said, like an alias.

[–] Sonotsugipaa@lemmy.dbzer0.com 3 points 2 months ago (2 children)

I don't think references are variables: you can't modify them, and AFAIR you can't have pointers to them, with the possible but unlikely exception of non-static member references.

[–] TheEntity@lemmy.world 6 points 2 months ago

An int& reference is just as much of a variable as int* const would be (a const pointer to a non-const int). "Variable" might be a misnomer here, but it takes just as much memory as any other pointer.

[–] firelizzard@programming.dev 4 points 2 months ago

For references within a scope, you’re probably right. For references that cross scope boundaries (i.e. function parameters), they necessarily must consume memory (or a register). Passing a parameter to a function call consumes memory or a register by definition. If a function call is inlined, that means its instructions are copy-pasted to the call location so there’s no actual call in the compiled code.