use*_*991 -2 c++ pass-by-reference
我的类有一个对象数组,称之为Foo.它存储Foo* m_Foos在类中.假设它的值为[0],保证,并且Foo有一个叫做IsSetbool或其他东西的属性.
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];
}
Run Code Online (Sandbox Code Playgroud)
谁能解释为什么m_Foo [0] =/= returnValue?我的语法错误在哪里?
我希望m_Foo [0]与returnValue是相同的引用,Foo在内存中是相同的.
TryThis()不修改Foo存储在m_Foos数组中的对象.GetValue()将Foo对象分配m_Foos[0]给另一个Foo本地对象TryThis().一个副本是,分配新建分配FY的过程中进行. TryThis()然后修改副本,而不是原始副本.
如果要直接TryThis()修改原始Foo对象,则需要执行更类似的操作:
void TryThis()
{
Foo &returnValue = GetValue();
returnValue.IsSet = true;
// m_Foo[0] is set true.
}
Foo& GetValue()
{
return m_Foos[0];
}
Run Code Online (Sandbox Code Playgroud)
或这个:
void TryThis()
{
Foo *returnValue;
GetValue(returnValue);
returnValue->IsSet = true;
// m_Foo[0] is set true.
}
void GetValue(Foo* &container)
{
container = &m_Foos[0];
}
Run Code Online (Sandbox Code Playgroud)