deductiongu...::shared_ptr(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– NAME πŸ’–

deductionguidesforstd::shared_ptr β€” deductionguidesforstd::shared_ptr

Okay so first things first, bestie: this page is deductiongu...::shared_ptr(3), and it lives in the C++ Standard Libary corner of the universe. The name line is literally the same thing twice, and honestly? Iconic.

✨ Synopsis ✨

Defined in header <memory>:

template< class T >                                   (1) (since C++17)
shared_ptr( std::weak_ptr<T> ) -> shared_ptr<T>;
template< class T, class D >                          (2) (since C++17)
shared_ptr( std::unique_ptr<T, D> ) -> shared_ptr<T>;

These deduction guides are here for std::shared_ptr to account for the edge cases missed by the implicit deduction guides. That’s the whole reason they exist, no cap.

🚨 Important vibe check: there is no class template argument deduction from pointer types, because it is impossible to distinguish pointers obtained from array and non-array forms of new. So don’t try to make fetch happen there.

Both guides are since C++17:

  • (1) is the std::weak_ptr<T> one: shared_ptr( std::weak_ptr<T> ) -> shared_ptr<T>;
  • (2) is the std::unique_ptr<T, D> one: shared_ptr( std::unique_ptr<T, D> ) -> shared_ptr<T>;

πŸ§ͺ Example πŸ§ͺ

Run this code πŸ‘‡

// Run this code

#include <memory>

int main()
{
    auto p = std::make_shared<int>(42);
    std::weak_ptr w{p};    // explicit deduction guide is used in this case
    std::shared_ptr p2{w}; // explicit deduction guide is used in this case
}

The comments are doing the lore drop: both std::weak_ptr w{p}; and std::shared_ptr p2{w}; are using the explicit deduction guide in this case. Slay.


That’s the tea πŸ«– β€” served fresh from http://cppreference.com, dated 2024.06.10, and still answering to deductiongu...::shared_ptr(3). Mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from