Alt text:

Image that says:

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

int& a = b;

Zagorath
link
fedilink
English
28
edit-2
4M

I’ve used C but never C++. What does it mean for a variable’s type to be int&? From when I’ve used it, & would be used to create a pointer to a variable, but the type of that pointer would be int*.

edit:

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.

In my experience, it’s rare to see int& in day to day as a regular old lvalue… it essentially just allows you to alias a variable to another name. It’s much more common to see them used in function parameters to leverage pass by reference. In C++ pointers usually aren’t particularly useful compared to just passing things by reference since stack variables get auto-gc’d it’s the preferred style of frameworks like Qt and is extremely easy to use.

Here’s a breakdown if you want more information https://en.cppreference.com/w/cpp/language/reference

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
link
fedilink
English
34M

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.

Ethan
link
fedilink
English
44M

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.

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.

Crazy Diamond Inheritance!

Don’t see it. Could somebody give me a pointer?

Create a post

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

Rules:

  • Posts must be relevant to programming, programmers, or computer science.
  • No NSFW content.
  • Jokes must be in good taste. No hate speech, bigotry, etc.
  • 1 user online
  • 120 users / day
  • 257 users / week
  • 744 users / month
  • 3.72K users / 6 months
  • 1 subscriber
  • 1.48K Posts
  • 32.5K Comments
  • Modlog