使用存储shared_ptr<T>中的shared_ptr<常量 T>

Using a shared_ptr<const T> from a stored shared_ptr<T>

本文关键字:gt ptr lt shared 常量 中的 存储      更新时间:2023-10-16

我使用std::shared_ptr<T>存储了一些数据。

现在我想用它作为函数的const输入,所以我需要一个std::shared_ptr<const T>。我该怎么做?

我可以将std::shared_ptr<T>对象传递给期望std::shared_ptr<const T>的函数吗?

#include <memory>
void foo(std::shared_ptr<const int> ptr) {}
int main()
{
    auto ptr = std::make_shared<int>();
    foo(ptr);
}

你为什么不试试?