0

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 ) ?

4

2 回答 2

2

在这种情况下,您应该使用 const 参考

void CCamera::SetLookAt( const D3DXVECTOR3& lookAt )

案例 2 和案例 3 相同
并且创建向量时它的工作方式没有区别:
D3DXVECTOR ( D3DXVECTOR3( 8.0f, 0.0f, 5.0f )D3DXVECTOR3( x_component, y_component, z_component )

于 2013-05-16T13:14:27.440 回答
0

在情况 2 和 3(相同)中,您将指针传递给堆栈分配的匿名临时对象。这很好,因为在函数返回之前堆栈不会展开,因此您的指针将保持有效。

一旦 .SetLookAt 完成,匿名临时从堆栈中弹出,在 2 和 3 中,这就是为什么 {} 是多余的。

案例 1 将在没有您当前评论的删除的情况下泄漏。

于 2013-05-16T13:15:58.090 回答