Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are C++ smart pointers so unrestricted, i.e. may be reassigned or reset?

In both C++11 and boost, smart pointers can be nullptr. I wonder why. That means that smart pointers must be checked for being nullptr every time they are passed to interface method from uncontrolled client code. Obviously, such check is performed in run time.

What if there would be smart pointers that can be created only via make_shared or make_unique and cannot be reset or reassigned to nullptr or raw pointer? This approach allows to ensure that pointer is not nullptr in compile time.

For example, in Java we always must check if object is not null (bad). But in Swift, we can explicitly make sure that argument (or variable) is not null in compile time (good).

UPD: Well, thank you much for answers and comments. I got idea. But is there any popular libraries that supports non-nullity compile time guarantee alongside ownership, maybe smart pointer wrappers?

like image 388
George Sovetov Avatar asked Jan 09 '23 18:01

George Sovetov


1 Answers

std smart pointers exist for one reason—to implement the concept of ownership. Their responsibility is to clearly define who owns the pointee (i.e. who and how ensures its safe destruction).

Large parts of std are really composed of low-level basic building blocks. While they can be used straight away in client code, they are not supposed to be an all-encompassing solution. They give you single-purpose tools which you cna mix & match to create something you need.

The std smart pointers are eactly "raw pointers + ownership." Raw pointers can be null and can be reseated, so std smart pointers can as well. Nothing prevents you from creating your own "std smart pointer + non-nullity" class(es) and using them in your code.

On the other hand, there are very valid use cases for a null smart pointer. If std smart pointers enforce non-nullity, and you needed null-supporting smart pointers, you'd have a much harder time implementing that. It's easier to add a validity constraint than to remove it when you can only do it by adding to the original class.

like image 200
Angew is no longer proud of SO Avatar answered Apr 23 '23 04:04

Angew is no longer proud of SO