PDA

Просмотр полной версии : return-by-reference for Object field access


schmoozerd
29.08.2012, 01:41
Can somebody explain why we use return-by-reference to access object-fields?


const int32& GetInt32Value(uint16 index) const
{
MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index , false));
return m_int32Values[ index ];
}

const uint32& GetUInt32Value(uint16 index) const
{
MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index , false));
return m_uint32Values[ index ];
}

const uint64& GetUInt64Value(uint16 index) const
{
MANGOS_ASSERT(index + 1 < m_valuesCount || PrintIndexError(index , false));
return *((uint64*) & (m_uint32Values[ index ]));
}

const float& GetFloatValue(uint16 index) const
{
MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index , false));
return m_floatValues[ index ];
}

uint8 GetByteValue(uint16 index, uint8 offset) const
{
MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index , false));
MANGOS_ASSERT(offset < 4);
return *(((uint8*)&m_uint32Values[ index ]) + offset);
}

uint16 GetUInt16Value(uint16 index, uint8 offset) const
{
MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index , false));
MANGOS_ASSERT(offset < 2);
return *(((uint16*)&m_uint32Values[ index ]) + offset);
}

ObjectGuid const& GetGuidValue(uint16 index) const { return *reinterpret_cast<ObjectGuid const*>(&GetUInt64Value(index)); }

instead of normal return by value?

(Historical note: we do this since long forgotten times)

LordJZ
29.08.2012, 02:12
A discussion of a different yet related matter:
https://github.com/mangos/server/commit/611ca620aeb343138a9890acb6abc9d54ed679ed#commitcom ment-1673031

Vladimir
29.08.2012, 03:05
Code inlined and in result this is array access. For small size types i think no difference, it's just consistent with way how this used for large structures access for avoid copy constructor call.

zergtmn
29.08.2012, 06:48
I always pass POD types by value if they fit into 64-bit register.
As some people here said in theory compiler can optimize out access by reference but no one proved that average compiler can into such stuff.
Same with 'const'. I heard it can lead to better optimization by compiler but no one have real examples.

Vladimir
29.08.2012, 09:32
Maybe you right, i not have personal strong points against use return values instead refs for types fit to 64-bits.