The following code is taken from a DirectX tutorial and slightly modified by me:
void Initialize()
{
// case 1
m_camera.SetLookAt( new D3DXVECTOR3( x_component, y_component, z_component ) );
// case 2
m_camera.SetLookAt( &D3DXVECTOR3( x_component, y_component, z_component ) );
// case 3
{
m_camera.SetLookAt( &D3DXVECTOR3( x_component, y_component, z_component ) );
}
//more stuff to do here
}
void CCamera::SetLookAt( D3DXVECTOR3* pLookAt )
{
m_lookAt.x = pLookAt->x;
m_lookAt.y = pLookAt->y;
m_lookAt.z = pLookAt->z;
//delete pLookAt; // solution for case 1?
}
m_camera is instance of class CCamera, which has a private member D3DXVECTOR3 m_lookAt. The SetLookAt() function takes a pointer to a D3DXVECTOR3.
My question is, what is the difference between the ways this pointer is provided (case 1 and 2) ?
As far as my understanding goes, in case 1, the D3DXVECTOR is allocated from heap. The created pointer is passed to SetLookAt(), which copies the data and quits. Then, Initialize() quits, without releasing the memory taken by the D3DXVECTOR, resulting in a memory leak. The possible solution would be to uncomment the last line in SetLookAt().
In case 2, D3DXVECTOR is allocated on stack and its adress is passed to SetLookAt. This time, the D3DXVECTOR is freed only when Initialize() is finished.
Is my understanding correct? And what if I (in case 2) want the memory the D3DXVECTOR3 occupies to be freed as soon as the SetLookAt() function ends? Will wrapping the SetLookAt() in curly brackets (case 3) suffice to force the created D3DXVECTOR3 to be freed once SetLookAt is done?
Also, would it make any difference if the call to SetLookAt() (in all 3 cases), the vector would be called using literal values, e.g. D3DXVECTOR3( 8.0f, 0.0f, 5.0f ) instead of D3DXVECTOR3( x_component, y_component, z_component ) ?