Hi,
Lately I've been struggling a bit/ playing around with when to pass a const ref and when to pass by value, concercing XMFLOAT3/4's and XMFLOAT4X4 types. The advice I've got was to prevent doing it all by const ref, because the mentioned objects are quite 'small'. So I've thought of the following 'hand rule':
- when I retrieve a vector/ matrix I always return the class member by value
- when I have to pass a vector/ matrix to another object, I always do it as const ref
- always applying both rules should make it safe and prevent passing 'empty references'/ local adresses
Here's an example:
// INTERFACE
class objectTypeA
{
public:
DirectX::XMFLOAT4 GetPosition() const;
private:
DirectX::XMFLOAT4 mPositon;
};
// IMPLEMENTATION
XMFLOAT4 objectTypeA::GetPosition() const
{
return mPosition;
}
// INTERFACE 2
class objectTypeB
{
public:
void AdaptPosition(const DirectX::XMFLOAT4 &pPos);
private:
DirectX::XMFLOAT4 mPosition;
};
// IMPLEMENTATION
void objectTypeB::AdaptPosition(const XMFLOAT4 &pPos)
{
mPosition = pPos;
}
// CALLING THE FUNCTIONS
objectB.AdaptPosition(objectA.GetPosition());
?
?
?
?
When I have a mix of both, I get into situations where I always first have to create a local (scope) const variable, before I can pass it safe to another function that expects a const ref. Which I find makes my code not quite readable, here's an example:
// INTERFACE
class objectTypeA
{
public:
DirectX::XMFLOAT4& GetPosition() const;
private:
DirectX::XMFLOAT4 mPositon;
};
// IMPLEMENTATION
XMFLOAT4& objectTypeA::GetPosition() const
{
return mPosition;
}
// INTERFACE 2
class objectTypeB
{
public:
void AdaptPosition(const DirectX::XMFLOAT4 &pPos);
private:
DirectX::XMFLOAT4 mPosition;
};
// IMPLEMENTATION
void objectTypeB::AdaptPosition(const XMFLOAT4 &pPos)
{
mPosition = pPos;
}
// CALLING THE FUNCTIONS
const XMFLOAT4 localVec = objectA.GetPosition();
objectB.AdaptPosition(localVec);
I would appreciate your opinions and advice if this would be a good rule of thumb (or how you handle/ approach this).
It's basically the same for other relative small objects, like a XMFLOAT4X4 or a AABB/ OBB.