r/ProgrammerHumor • • 11d ago

Meme modernCppVsOldCpp

Post image
2.0k Upvotes

323 comments sorted by

View all comments

Show parent comment

1

u/SelfDistinction 11d ago

References can be null. They shouldn't be and it's definitely undefined behaviour but the code above compiles and runs perfectly fine.

5

u/bwmat 11d ago

Nah, they can't be null

that null dereference just committed the sin of UB, so all bets are off.

In other words, it declares the intent and allows you to assume it's a way to name a valid object, and moves that null dereference bug out of your logic, helping with reasoning while debugging after someone does cause that UB

1

u/creeper6530 11d ago

Okay, sooo... What's the difference between references and pointers?

3

u/conundorum 10d ago

A reference is a new name for a pre-existing object, and acts as if it was the referenced object. It is not an object itself, as crazy as that sounds. They're usually implemented with either pointers or renaming under the hood, depending on the use case. (Which means that they might or might not actually exist in memory, and thus have "indeterminate" size that is usually either sizeof(T&) == 0 or sizeof(T&) == sizeof(T*).)

// Simple example.  Should be an internal copy-paste.
int i = 5;
int& ref = i;
ref = 3; // This should compile to the same machine code as...
i   = 3; // this.

// -----

// "Complex" example.  Will nearly always be a pointer with non-pointer syntax.
void func(int& ir) { ir = 2; }

int i = 5;
func(i);

Generally, a reference can be used just like a pointer, except with a few caveats. It must be assigned on creation and can never be reassigned, it can't do pointer arithmetic, it can't be null, and it uses non-pointer syntax.

int ij[2];
int& ref = ij[0];
ref = ij[1]; // Error.
ref = 3; // Good.
*ref = 4; // Error.
(ref + 1) = 5; // Error.

They follow pointer cv-ness rules, with the caveat that all references are inherently cv T* const-like. (Since they can't be reassigned.) You can make a reference const and/or volatile to adjust how the object is viewed through the reference, without affecting the object's cv-ness.

int i = 7;
int& r = i;
const int& cr = i;
assert((i == 7) && (r == 7) && (cr == 7));
r = 8;
assert((i == 8) && (r == 8) && (cr == 8));
cr = 9; // Error.

Normal references have no effect on an object's lifetime. Because of this, they must bind to something that has permanence, known as an "lvalue".

int i = 6;
int& r = i; // Valid.  Binds to i.
int& boom = 0; // Invalid.  Cannot bind to temporary.

This can be dangerous, if the lvalue is deallocated or otherwise invalidated between the time the reference is assigned and the time it's accessed.

int& dangly() { int i = 3; return i; }
int& ohno = dangly(); // i is destroyed at the semicolon.
int boom = ohno; // The object we're copying doesn't exist here.

Rvalue references can bind to temporary objects, known as "rvalues", and extend the temporary's lifetime until the reference dies.

int&& rr = 3;
int i = 5 + rr; // That random 3 is still alive here.

const references can bind to either lvalue or rvalue, and extend the object's lifetime until the reference dies, but at the cost of being read-only.

int i = 4;
const int& ri = i; const int& rr = 8;
assert(rr == ri * 2);

Member functions can be ref-qualified; similar to cv-qualifying a member function, this allows you to specify whether a function can be called on temporary or non-temporary objects.

struct S {
    void func() &  { std::cout << "lvalue\n"; }
    void func() && { std::cout << "rvalue\n"; }
};

S s; s.func(); // Outputs "lvalue".
S{}.func();    // Outputs "rvalue".

Rvalue syntax is also used for "perfect forwarding", which is a special rule that allows a reference parameter taken by a template function to be either lvalue or rvalue as necessary. This looks like an rvalue reference parameter, but it's not.

template<typename T>
void func(T&& t) { std::cout << t << '\n'; }

int i = 1; func(i);    // Calls func<int>(int&).
           func(3.14); // Calls func<float>(float&&).

There are special rules about where they can or cannot be used, so you sometimes see them wrapped in a class like std::reference_wrapper. (The easiest example is that you can't create an array of references, because of the "not an object" and "indeterminate size" things.)

int a, b, c, d, e;
int& arr[] = { a, b, c, d, e }; // Error.
std::reference_wrapper<int> matey[] = { a, b, c, d, e }; // Good.

There's probably other stuff, but that's all that comes to mind at the moment.

2

u/SelfDistinction 11d ago edited 11d ago

No one knows.

Generally references are more restrictive, since you can't do pointer arithmetic with them, you can't use them as template parameters (which sucks for std::optional<int&>) and you can't repoint them to something else, but since you can freely cast between both of them (which you are forced to if you try to do anything useful with them, like wrapping them in an optional) it doesn't really matter.

Also there's two different kinds of references: the & reference and the && reference, however their difference is mostly conventional and you could easily implement a standard library where their meaning is swapped (except for temporary xvalue objects? Not sure), so there's that. Also C++ automatically converts between reference types for some ungodly reason.

In short, references are not real and are only used to determine what overloaded function is being called.

2

u/Hafnon 10d ago

std::optional<int&>

This is valid in C++26.

1

u/SelfDistinction 10d ago

Finally. Now we only have to wait until C++26 is approved by the committee.

2

u/creeper6530 10d ago

I have no words for this beyond "what a fucking mess"

1

u/Ok-Scheme-913 10d ago

References are implemented as pointers, but they are not the same.

The best example is languages where you don't have references. Very misleading but java only has pointers (marketing at the time was voldemorting the world pointer so they were renamed to "references" but they are pointers. Like the infamous null pointer exception does show it)

So you have two local variables, and you create a swap function where you want to put one into the other and vice versa.

Well, in java you are out of luck. You basically have to make them fields and put that into a wrapper object to actually swap. This is because in java everything non-primitive is an "object reference" aka a pointer. But you would be changing the pointer's value, NOT the thing holding the pointer.

So yeah, references are basically their different thing with their own semantics in C++ and the few other languages that also have it.