Add implicit conversion from unique_ptr to T*

前端 未结 1 404
余生分开走
余生分开走 2021-01-12 08:01

General Question: Without going into whether or not it\'s a good idea, how can I add an implicit conversion operator to a class that has already been defined? For exa

相关标签:
1条回答
  • 2021-01-12 09:03

    If you don't want to use std::unique_ptr<>::get() function, you can:

    1. Define a free function that takes a std::unique_ptr and returns the raw pointer returned by get, although I don't think it really makes your code better, like:

      // free function
      template<typename T>
      T* get_raw_ptr(const std::unique_ptr<T>& up)
      {
          return up.get();
      }
      

      Conversions of unique_ptr to raw pointers are OK, but they have to be explicit. Implicit conversion may lead to lots of headaches, since they may happen when you least expect them.

    2. It is a bad idea to derived from std::unique_ptr, as the latter is not made to be used as a base class (doesn't have a virtual destructor). In general, it is bad to derive from Standard Library classes. However, if you really insist, you can use a wrapper in which you define the implicit conversion operator, like:

      // wrapper
      template <class T, class Deleter = std::default_delete<T>> 
      class unique_ptr_wrapper: public std::unique_ptr<T, Deleter>
      {
      public:
          using std::unique_ptr<T, Deleter>::unique_ptr; // inheriting base ctors
          operator T* () const {return this->get();}
      };
      

    and use is simply like

        // wrapper usage:
        unique_ptr_wrapper<int> upw{new int{42}};
        int* p = upw; // implicit conversion OK
    
    1. 1 and 2 can help you, so you may improve your life ;)
    0 讨论(0)
提交回复
热议问题