假设我们有以下函数:
有没有一种(安全的)方法将
void doStuff(const std::vector<std::shared_ptr<const Foo>>& fs) { }
有没有一种(安全的)方法将
std::vector<std::shared_ptr<Foo>>
传递给这个参数?例如:std::vector<std::shared_ptr<Foo>> foos;
doStuff(foos);
这种隐式转换失败了,但是可以通过强制类型转换来安全地完成吗?(从理论上看,这似乎是安全的,因为doStuff
函数将无法修改向量,也无法修改其中的对象。)
const_cast
? - jtbandesreinterpret_cast
或 c 式转换。我不明白为什么const_cast
可以解决这个问题。如果只是一个const_cast
,它可能会被很好地定义。const_cast
无法将std::vector<const T>&
转换为std::vector<T>&
。 - François Andrieuxconst
也会允许被调用者修改底层对象。有没有什么方法可以避免这种情况?我想,如果shared_ptr
只有T* operator->();
和const T* operator->() const;
,那么它就可以与const vector<shared_ptr<T>>
正常工作,但事实并非如此... - jtbandes