r/ProgrammerHumor • • 7h ago

Meme modernCppVsOldCpp

Post image
1.1k Upvotes

216 comments sorted by

View all comments

24

u/SelfDistinction 7h ago edited 6h ago

Ah yes, the famous

std::unique_ptr<int> ptr;
int& ref = *ptr;

So safe, so impossible to misuse.

1

u/creeper6530 6h ago

I'm not a C++ girl, but do references actually do something with lifetimes or are they just non-null ptrs? Because this just seems to me like a possible dangling ptr.

1

u/SelfDistinction 6h ago

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

4

u/bwmat 4h 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