gpt4 book ai didi

c++ - 将 map> 转换为 map>?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:52:47 26 4
gpt4 key购买 nike

我正在存储一个 std::mapstd::shared_ptr<V>作为值(value)。

从一个函数中,我想返回对该 map 的引用,但使用 std::shared_ptr<const V>作为值类型,这可能吗?

这是我想要实现的:

#include <map>
#include <memory>

struct A {
std::map<int, std::shared_ptr<int>> map;

const std::map<int, std::shared_ptr<const int>>& ret1() const {
return map;
}
};

但是这段代码编译失败:

error: invalid initialization of reference of type 
'const std::map<int, std::shared_ptr<const int> >&'
from expression of type 'const std::map<int, std::shared_ptr<int> >'

谢谢

最佳答案

类型 T 和类型 const T 是相关但最终不同的类型。如果您不希望 ret1 的调用者修改映射中的值,则返回映射的拷贝,或者接受对映射的引用作为参数并将键和值复制到那个。

关于c++ - 将 map<K, shared_ptr<V>> 转换为 map<K, shared_ptr<const V>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13873893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com