C++ 铸造地图<;K、 共享\u ptr<;V>&燃气轮机;映射<;K、 共享\u ptr<;常数V>>;?
我将C++ 铸造地图<;K、 共享\u ptr<;V>&燃气轮机;映射<;K、 共享\u ptr<;常数V>>;?,c++,casting,constants,C++,Casting,Constants,我将std::shared\u ptr的std::map存储为值 从一个函数中,我想返回对这个映射的引用,但是使用std::shared\u ptr作为值类型,这可能吗 以下是我想要实现的目标: #include <map> #include <memory> struct A { std::map<int, std::shared_ptr<int>> map; const std::map<int, std::share
std::shared\u ptr
的std::map
存储为值
从一个函数中,我想返回对这个映射的引用,但是使用std::shared\u ptr
作为值类型,这可能吗
以下是我想要实现的目标:
#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;
}
};
#包括
#包括
结构A{
地图;
常量std::map&ret1()常量{
返回图;
}
};
但此代码无法编译:
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> >'
错误:类型的引用初始化无效
“const std::map&”
来自“const std::map”类型的表达式
谢谢类型
T
和类型const T
是相关的,但最终是不同的类型。如果您不希望ret1
的调用者修改映射中的值,请返回映射的副本,或接受对映射的引用作为参数,并将键和值复制到该映射中