Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert from boost::shared_ptr<T> to boost::shared_ptr<const T>

Tags:

c++

boost

class T
{};

class UseT
{
public:
    //...
    boost::shared_ptr<const T> getT() const
    {
        return m_t;
    }
private:
    boost::shared_ptr<T> m_t;
};

Question> What are the rules used when we convert from boost::shared_ptr<T> to boost::shared_ptr<const T>?

like image 976
q0987 Avatar asked Jun 20 '26 01:06

q0987


1 Answers

shared_ptr<T> has a converting constructor that allows it to be constructed from shared_ptr<U> if it would be valid to convert from U* to T*, mirroring how built-in pointers work.

template<typename U>
  shared_ptr(const shared_ptr<U>& other);

(For std::shared_ptr the constructor can only be called if U* is convertible to T*, but for boost::shared_ptr I'm not sure if it checks that, or you just get a compiler error for invalid conversions.)

Since T* can be converted to const T*, the constructor allows you to create a shared_ptr<const T> from a shared_ptr<T>.

like image 195
Jonathan Wakely Avatar answered Jun 21 '26 18:06

Jonathan Wakely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!