gpt4 book ai didi

c++ - 将事物保存在 vector 中会使内部引用无效,如何解决?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:56:18 26 4
gpt4 key购买 nike

我有一个这样的结构:

struct A {
B b;
C c;
}

其中 c 保留对 b 的引用。我将 A 保存在一个 vector 中:

std::vector<A> as;

将新元素推回 vector 时,它可能会在内存中移动。这改变了 b 的地址并使 c 对 b 的引用无效。有没有比将 b 的数据移出结构并保留指向它的指针更好的方法来解决这个问题?

最佳答案

当 vector 重新分配内存时,它会构造对象的拷贝并销毁旧对象(使用复制或移动构造函数)。

由于 A、B、C 不再是简单可初始化的(该引用需要一些特定于类的逻辑才能正确设置),您需要提供代码来执行此操作。

struct B {};
struct C {
B& b_;

C() = delete; // in C++11, or just declare but don't implement
explicit C(B& b) : b_(b) {}
};
struct A {
B b;
C c;
A() : c(b) {}
A(A const &other) : b(other.b), c(b) {}
A& operator= (A const &other) {
b=other.b;
// c already refers to the correct b ...
return *this;
}
};

请注意,除了引用之外,此 C 没有其他成员。如果您的 C 包含其他应该被复制/移动/分配的内容,只需保留引用并仅修改那些成员。

关于c++ - 将事物保存在 vector 中会使内部引用无效,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18288752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com