Cast from shared pointer to shared pointer to const

2.2k views Asked by At

The following code does not compile:

#include <iostream>
#include <memory>

class A
{
public:
    A( )
        : m_i( new int )
    { }

    std::shared_ptr< const int >&
    get( )
    {
        return m_i; // <-- invalid initialization of reference of type
                    //     'std::shared_ptr<const int>&' from 
                    //     expression of type 'std::shared_ptr<int>'
    }

private:
    std::shared_ptr< int > m_i;
};


int main( )
{
    A a;
    auto& i = a.get( );

    std::cout << *i << std::endl;
    return 0;
}

How is it possible to cast from a shared pointer to a shared pointer to constant object? static_cast also fails.

2

There are 2 answers

5
Bathsheba On

Change your get to

std::shared_ptr<const int> get( )

which will remove what is essentially a dangling reference, and compilation will succeed.

2
Chris Drew On

If the caller of A::get only wants to observe m_i and doesn't want to obtain shared ownership then I would just return a pointer-to-const:

const int* get( ) { return m_i.get(); }

Holding a reference to a smart-pointer is no safer than a raw pointer. If the owner of the smart pointer goes out of scope you will have a dangling reference to a smart pointer.