nyarlathotep108
nyarlathotep108

Reputation: 5523

Cast from shared pointer to shared pointer to const

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.

Upvotes: 4

Views: 2512

Answers (2)

Chris Drew
Chris Drew

Reputation: 15334

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.

Upvotes: 8

Bathsheba
Bathsheba

Reputation: 234685

Change your get to

std::shared_ptr<const int> get( )

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

Upvotes: 9

Related Questions