Game Development Reference
In-Depth Information
Listing 22-4. Using
unique_ptr
and
shared_ptr
#include <memory>
class Simple
{
private:
int variable{ 0 };
public:
Simple()
{
std::cout << "Constructed" << std::endl;
}
~Simple()
{
std::cout << "Destroyed" << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
using UniqueSimplePtr = std::unique_ptr<Simple>;
UniqueSimplePtr pSimple1{ new Simple() };
std::cout << pSimple1.get() << std::endl;
UniqueSimplePtr pSimple2;
pSimple2.swap(pSimple1);
std::cout << pSimple1.get() << std::endl;
std::cout << pSimple2.get() << std::endl;
using IntSharedPtr = std::shared_ptr<int>;
IntSharedPtr pIntArray1{ new int[16] };
IntSharedPtr pIntArray2{ pIntArray1 };
std::cout << std::endl << pIntArray1.get() << std::endl;
std::cout << pIntArray2.get() << std::endl;
return 0;
}
As the name suggests,
unique_ptr
is used to ensure that you only have a single reference to
allocated memory at a time. Listing 22-3 shows this in action.
pSimple1
is assigned a
new Simple
pointer and
pSimple2
is then created as empty. You can try initializing
pSimple2
by passing it
pSimple1
or using an assignment operator and your code will fail to compile. The only way to pass
the pointer from one
unique_ptr
instance to another is using the
swap
method. The
swap
method
moves the stored address and sets the pointer in the original
unique_ptr
instance to be
nullptr
.
The first three lines of output in Figure
22-4
show the addresses stored in the
unique_ptr
instances.