C++ Keywords - auto
Be precise with use of auto. Knowing that things are constant or that indirections are occurring is very valuable information to readers.
const auto&: a reference to non-const / const
const auto*: when the type is a pointer.
auto For returned
These 2 are equivalent:
const auto foo = GetFoo();(Preferred)
const auto& foo = GetFoo();
This does not compile.
const auto* foo = GetFoo();
auto* x = y expects that
y is a C++ pointer. But
std::unique_ptr<T> is just an object that behaves like a pointer and takes care of ownership. Other than that, it is just a regular C++ class, not a regular pointer, like
Do not do:
const auto* foo = GetFoo().get();
It destructs the pointer when the statement ends, leaving thing as a dangling pointer.
GetFoo will return a temporary object, you get the pointer to the underlying
Foo* and assign it to
foo. However as soon as that line is execute, the temporary
unique_ptr will be destroyed and the underlying
Foo object is freed, so now
foo is a dangling pointer to the freed memory.