Passing an CComPtr<IDirect3DDevice9> to another class via its constructor

Started by
2 comments, last by iMalc 10 years, 10 months ago

How do I safely pass a CComPtr<IDirect3DDevice9> to another class via its constructor? Do I pass by reference or by value? Which way does the CComPtr actually add to the reference counter? And do I store it as raw pointer or another CComPtr in the newly created class?

I'm bit overwhelmed by the pointers, references and memory leaks I have to deal with coming from C# :-/

Thanks for your help in advance,

Jordy

Advertisement
In the new class you want to store a CComPtr, not a raw pointer. Using a combination of raw pointers and CComPtrs defeats the purpose of using a CComPtr in the first place. A CComPtr will increment the reference count of the pointed to interface whenever that interface is passed to a CComPtr constructor or assignment operator. You can pass a CComPtr by value or reference, though pass by value is generally inefficient if you're just going to sink that value into another CComPtr.

So if this is my class:


class MyClass
{
private:
	CComPtr<IDirect3DDevice9> d3ddev;

public:
	MyClass(IDirect3DDevice9 * _d3ddev)
	{
		this->d3ddev = _d3ddev;
	} 
};

And I would create an instance of it like this:


CComPtr<IDirect3DDevice9> d3ddev;

InitDevice()
{
    // d3ddev gets inititialized here
}

SomeFunction()
{
    InitDevice();
    MyClass myclass1(d3ddev);
}

Then that would be fine?

Other than using the constructor initialisation list, yes that is the right way to do it.

The parameter should be a raw type, as you have it, and the member should be a smart type, again as you have it.

"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement