参考未返回

Reference not returning?

本文关键字:返回 参考      更新时间:2023-10-16

我的类有一系列对象,称其为 Foo。它在同类中存储为Foo* m_Foos。假设它具有[0]的值,并且保证和Foo具有称为IsSet的属性,它只是一个bool或其他东西。

void TryThis()
{
   Foo returnValue;
   GetValue(returnValue);
   returnValue.IsSet = true;
   if(m_Foo[0].IsSet != returnValue.IsSet)
   {
      // ERROR!!!!
   }
}
void GetValue(Foo &container)
{
   container = m_Foos[0];
}

谁能解释为什么m_foo [0] =/= returnValue?我的语法中的错误在哪里?

我希望m_foo [0]与returnValue相同,在内存中相同的 Foo

TryThis()没有修改存储在m_Foos数组中的Foo对象。

GetValue()Foo对象从m_Foos[0]分配给TryThis()本地的另一个Foo对象。在该评估期间正在制作副本。然后,TryThis()正在修改副本,而不是原始副本。

如果您希望TryThis()直接修改原始Foo对象,则需要做更多这样的事情:

void TryThis()
{
   Foo &returnValue = GetValue();
   returnValue.IsSet = true;
   // m_Foo[0] is set true.
}
Foo& GetValue()
{
   return m_Foos[0];
}

或以下:

void TryThis()
{
   Foo *returnValue;
   GetValue(returnValue);
   returnValue->IsSet = true;
   // m_Foo[0] is set true.
}
void GetValue(Foo* &container)
{
   container = &m_Foos[0];
}