繁体   English   中英

从共享指针转换为指向const的共享指针

[英]Cast from shared pointer to shared pointer to const

以下代码无法编译:

#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;
}

如何从共享指针转换为常量对象的共享指针? static_cast也失败了。

改变你的get

std::shared_ptr<const int> get( )

这将删除本质上是一个悬空引用,编译将成功。

如果A::get的调用者只想观察m_i并且不想获得共享所有权,那么我只返回一个指向const的指针:

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

持有对智能指针的引用并不比原始指针更安全。 如果智能指针的所有者超出范围,您将拥有对智能指针的悬空引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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