简体   繁体   中英

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.

Change your get to

std::shared_ptr<const int> get( )

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM