当矢量改变容量时,有什么方法可以更新指针/参考值



例如:如果我使用一个变量,该变量引用了向量的一个元素,然后向量的容量发生了变化,则我的引用将成为无效引用。

#include <vector>
#include <iostream>
std::vector<int> v = {1, 2, 3};
int main() {
int &r = v[0];
std::cout << r << std::endl;
v.reserve(256);
std::cout << r << std::endl;
std::cout << v[0] << std::endl;
}

有什么办法可以避免这种情况吗?或者只是不引用向量元素?

如果将向量中的对象存储为std::unique_ptr或std::shared_ptr,则可以使用std::unique_ptr::get((获取指向底层对象的观察指针(如果取消引用智能指针,则为引用(。这样,即使智能指针的内存位置在调整大小时发生变化,观察指针也指向同一对象。

#include <memory>
#include <vector>
#include <iostream>
int main() {
std::vector<std::unique_ptr<std::string>> v;
std::unique_ptr<std::string> s = std::make_unique<std::string>("Hello");
//Use either a reference or a pointer
const std::string* obs_pointer = s.get();
const std::string& ref = *s;
v.push_back(std::move(s));
v.reserve(256);
std::cout << ref;
std::cout << *obs_pointer;
}

稳健且最小的解决方案是存储索引,而不是使用指针或引用。

您可以将索引抽象为一个类型。

以下内容(为了清晰起见,非模板(:

#include <vector>
#include <iostream>
class vector_ref
{
public:
vector_ref(std::vector<int>& v, size_t ix) : m_v(v), m_ix(ix) {}
operator int& () { return m_v[m_ix]; }
int operator=(int x) { m_v[m_ix] = x; return x; }
private:
std::vector<int>& m_v;
size_t m_ix;
};
void foo(int& v) { v = 999; }
int main() {
std::vector<int> v = {1, 2, 3};
vector_ref r(v, 0);
std::cout << r << std::endl;
v.reserve(256);
std::cout << r << std::endl;
r = 21;
std::cout << v[0] << std::endl;
foo(r);
std::cout << v[0] << std::endl;
}

最新更新