SimplifyC++ Article
what c++20 and c++23 add to smart pointers
what c++20 and c++23 add to smart pointers.
C++20 and C++23 introduced several enhancements to smart pointers, making them more versatile and easier to use. Here's a summary of the key additions:
C++20:
Deducible templates for
std::unique_ptrandstd::shared_ptr: You can now create unique and shared pointers without explicitly specifying the template arguments. The compiler will deduce the type from the initializer. For example:
std::unique_ptr p = new int(42); // Deduces the type as std::unique_ptr<int>std::make_uniqueandstd::make_sharedfor deducible templates: These functions now support the new deducible templates, making it even easier to create smart pointers. For example:
std::unique_ptr p = std::make_unique<int>(42);std::weak_ptr::locknow returns an optional: Thelockmethod ofstd::weak_ptrnow returns anstd::optionalinstead of a raw pointer. This avoids potential null pointer dereferences if the object has been deleted.std::shared_ptr::operator bool: Thestd::shared_ptrnow has aboolconversion operator, allowing you to use it directly in boolean contexts to check if it points to a valid object.
C++23:
std::shared_ptr::atomic: This new member function allows you to atomically access and modify the reference count of astd::shared_ptr. This is useful in multi-threaded environments where multiple threads need to share ownership of an object.std::shared_ptr::get_deleter: This new member function returns a copy of the deleter associated with thestd::shared_ptr. This can be useful for debugging or customizing the deletion behavior.std::weak_ptr::has_value: This new member function checks if thestd::weak_ptrpoints to a valid object without attempting to lock it. This can be more efficient than usinglockin cases where you only need to know if the object exists.
These enhancements make smart pointers even more powerful and convenient to use in C++20 and C++23. They improve readability, safety, and performance, making it easier to write correct and efficient code.