让
class A
{
std::vector<std::shared_ptr<int>> v_;
};
现在我想通过两个公共成员函数来访问v_
std::vector<std::shared_ptr<int>> const & v() { return v_; }
并且
std::vector<std::shared_ptr<int const> const & v() const { TODO }
尽管如此,我无法用 return v_;
替换 TODO
。
一个选项是不返回引用而是返回一个副本。除了明显的性能损失外,这也会使接口略微不太理想。
另一种选择是将 TODO
等于 return reinterpret_cast<std::vector<std::shared_ptr<int const>> const &>(v_);
我的问题是,这是未定义行为吗?或者,有更好的选择吗,最好不要使用 reinterpret_cast
?
int
(或const int
)的指针?如果您有一个指向“数组”的指针,那么使用向量会更合适吗? - Some programmer dude&
而只能返回const &
。 - Xophv_
的范围循环,例如。在我的实际代码中,我更喜欢返回一个非 const 的std::vector<std::shared_ptr<int>> & v()
,以便外部用户甚至可以更改v_
。 - Xoph