假设我们有一些类,比如说class Apple,想要存储一个std::vector包含的类Apple.
向量是否应包含指针,引用或普通对象?
std::vector<Apple*> vector; // Definitely won't copy the Apple on lookup,
// but I would prefer not to use pointers if I don't have to
std::vector<Apple&> vector; // Seems circuitous?
std::vector<Apple> vector; // I don't know if this copies the Apple on each lookup
Run Code Online (Sandbox Code Playgroud)
我的目标是在打电话时这样做
Apple& a = vector[4];
Run Code Online (Sandbox Code Playgroud)
该Apple不会被复制.
我已经使用C++超过一年了,我一直在努力解决这个问题.是否有一个简单的解释为什么这三种方法中的一种是最佳实践?
Zet*_*eta 20
使用类型T.请记住,operator[]返回一个(const)引用,所以你的Apple&工作正常:
T& vector<T>::operator[](size_t);
const T& vector<T>::operator[](size_t) const;
Run Code Online (Sandbox Code Playgroud)
这就是为什么你可以使用vec[3].make_older()如果return_type Apple::make_older(void)存在的开始.
但是,请记住,有许多方法会使引用无效,所以
Apple& reference = vec[3];
vec.push_back(other_apple);
reference.get_eaten();
Run Code Online (Sandbox Code Playgroud)
如果push_back重新分配引用的apple,可能会导致未定义的行为.
Dav*_*rtz 11
使用:
std::vector<Apple> vector; // I don't know if this copies the Apple on each lookup
Run Code Online (Sandbox Code Playgroud)
虽然所有这些都可以实现您的目标(查找永远不会复制),但这是允许vector拥有其中的Apples以便生命周期得到合理管理的目标.
| 归档时间: |
|
| 查看次数: |
1020 次 |
| 最近记录: |