Notification texts go here Contact Us Buy Now!

C++ std:.auto_ptr or std::unique_ptr (to support multiple compilers, even old C++03 compilers)?

  1. Use boost::unique_ptr:
    #include 
    
    class MyClass {
    private:
      boost::unique_ptr m_ptr;
    };
    
  2. Conditionally use auto_ptr or unique_ptr:
    #if __cplusplus < 201103L
    #include 
    #else
    #include 
    #endif
    
    class MyClass {
    private:
    #if __cplusplus < 201103L
      std::auto_ptr m_ptr;
    #else
      std::unique_ptr m_ptr;
    #endif
    };
    
  3. Use a preprocessor macro:
    #define AUTO_PTR std::auto_ptr
    
    class MyClass {
    private:
      AUTO_PTR m_ptr;
    };
    

    Note that this macro approach is not recommended, as it can lead to subtle errors if you are not careful.

  4. Wrap the std:: smart pointer in your own defined template smart pointer class:
    template 
    class MySmartPtr {
    private:
      std::unique_ptr m_ptr;
    
    public:
      MySmartPtr(T* ptr) : m_ptr(ptr) {}
    
      T* get() { return m_ptr.get(); }
    
      T* release() { return m_ptr.release(); }
    };
    
    class MyClass {
    private:
      MySmartPtr m_ptr;
    };
    

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.