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.
Change your
get
towhich will remove what is essentially a dangling reference, and compilation will succeed.