[英]Updating a Reference as a Class Member
I'm pretty sure I'm misunderstanding references. 我敢肯定我误会了参考资料。
In the code below, I'd like to initialize A to have a state, but at some time in the future, when I call init (registering a B object to A), I'd like stateB variable to show the value of the B state. 在下面的代码中,我想将A初始化为具有状态,但是在将来的某个时候,当我调用init(将B对象注册到A)时,我想使用stateB变量来显示A的值。 B状态。
I can do this by making stateB a pointer, then initializing some memory in A's constructor and setting it to the default, then moving this pointer and deleting the memory when calling init. 我可以通过将stateB用作指针,然后在A的构造函数中初始化一些内存并将其设置为默认值,然后移动该指针并在调用init时删除内存来做到这一点。
Can I do this without stateB being a pointer by changing the reference of stateB to be b->state? 在将stateB的引用更改为b-> state的情况下,可以在没有stateB作为指针的情况下执行此操作吗?
Class A {
public:
int stateB = 0;
B *b = nullptr;
void init(B *b) {
&state = &b->state;
}
}
class B {
public:
int state = 1;
}
First off, this line is invalid: 首先,此行无效:
&state = &b->state;
You cannot assign to the address of state
. 您不能分配给state
的地址。 All you can do is state = b->state
, but that will not meet all your required semantics. 您所能做的就是state = b->state
,但这将无法满足您所有必需的语义。 That leaves you with a couple options. 这给您留下了两个选择。 You can make stateB
a pointer: 您可以使stateB
成为指针:
class A {
int* stateB;
public:
void init(B* b) {
stateB = &b->state;
}
};
But you cannot make stateB
a reference. 但是您不能将stateB
用作参考。 References must be initialized and can never be reassigned. 引用必须初始化,并且永远不能重新分配。 So if you want your A
to be reinitialized to multiple different B
s, then you'll have to stick with a pointer. 因此,如果您希望将A
重新初始化为多个不同的B
,则必须坚持使用指针。 However, if you want to effectively bind A
to a single B
, then a reference is fine: 但是,如果要有效地将A
绑定到单个B
,则可以使用引用:
class A {
int& stateB;
public:
A(B& b) : stateB(b.state) { } // must be initialized
// in the ctor
// this A can only ever point to this
// specific B
{ };
Note that both of these solutions can suffer from a dangling pointer/reference if the B
goes out of scope while you still have the A
that is referring to its state. 请注意,如果B
超出范围,而您仍然拥有A
引用其状态,则这两种解决方案都可能遭受悬挂的指针/引用的困扰。 One solution to that problem would be to simply use shared_ptr
: 解决该问题的一种方法是只使用shared_ptr
:
class A {
std::shared_ptr<int> stateB;
public:
A(std::shared_ptr<B> b)
: stateB(b, &b->state) // "aliasing" constructor
{ }
};
That makes sure that the B
will stay alive at least as long as the A
. 这样可以确保B
至少与A
一样存活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.