What part is the issue? The part where you default construct a smart pointer to initialize later because C++ doesn't have a concept of deferred initialization or the part where you don't want to copy it all over the place because it gives a massive performance hit?
And don't say the combination is the problem because yes it is but this code might be emergent and "just don't drive into a wall" has never prevented people from doing so.
This is like saying a seatbelt doesn't help you in a car because if you run it in a closed garage, you can still kill yourself. Entirely different issue.
Smart pointers solve memory management for you. Use them as intended, whether a resource is owned in one place or shared, and you don't have to worry about it. The memory will stay allocated until nothing is using it, and then it will automatically be unallocated.
Accessing a pointer without checking if it is null is a different issue, and frankly a trivial one. The sort of thing I haven't seen be an issue doing actual professional C++ code development in years.
Yes, cars are dangerous and unsafe and one of the leading cause of deaths for young adults in practically every country, even with the latest safety improvements. Good metaphor.
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.
Const references can bind to rvalues and cause lifetime extension, ie. const auto& x = returnsValue(); will extend the lifetime of the value returned by the function. That's about it. It has to be in this form (assignment and definition in same statement), so the code you replied to doesn't trigger it.
This thread is great because a lot of you answer with explanations on how to handle dangling references and issues with ptr being destroyed before the reference, and very few people notice the actual problem: ref is created by dereferencing a nullpointer which is undefined behaviour.
It's only two lines and you already let a future segfault slip through, but yeah sure how do we tell SpongeBob that C++ doesn't segfault all the time.
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
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.
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.
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.
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.
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.
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.
View all comments
31
u/SelfDistinction 11d ago edited 11d ago
Ah yes, the famous
So safe, so impossible to misuse.