So from the top-voted answer to this question, it appears that using raw pointers for storage isn't frowned upon so much. However, then what is the point of a std::weak_ptr
? I thought that storage was the exact purpose of that class. If so, is there any circumstance in which a raw pointer is considered good, valid code? If there isn't any, what is the point of having them in the language? Is it simply historical artifact?
2 Answers
weak_ptr
is solely usable in conjunction with shared_ptr
. It also has a little memory overhead while some weak pointers remain (a struct on the heap holding the strong and weak refcounts).
It is fine to use raw pointers if you can assure yourself of the relative lifetimes of the pointer vs. what it points to and prevent dereferencing the pointer while it dangles.
The smart pointers are tools to help with that (under the hood they use raw pointers).
For example unique_ptr
sets the lifetime of the pointed to object the same as the pointer with extra functionality for explicit reset
or release
. The memory footprint for a unique_ptr is the same as a raw pointer unless you use a stateful deleter.
A weak_ptr can actually extend the lifetime of a shared_ptr.
To access what a weak_ptr points to, you have to call lock() on it. This temporarily upgrades it to a shared_ptr. You can then use this pointer without the danger of it going away while you are using it. You don't get that guarantee when you are using naked pointers.
new, delete and raw pointers are not completely useless. These are the building blocks of what smart pointers are built upon!
-
1technically lock creates a new
shared_ptr
while the originalweak_ptr
remains untouched Commented Jun 16, 2014 at 13:00
new
anddelete
keywords are completely useless, aren't they? It's not C code, and if pure C++ shouldn't have raw pointers, then...new
anddelete
are historical artifacts of C++, not C. New C++ compilers must still be able to compile old C++ code... Yeah.new
anddelete
are NOT historical artifacts of C++. For example, to writestd::unique_ptr
, you will need them. Thus, they are not obsolete. I have no idea why people feel that low level constructs are obsoleted by high level constructs for all use cases. It's sad.