Conteúdo do Curso
C++ Smart Pointers
C++ Smart Pointers
Inner Workings of a Unique Pointer
When you create a new unique pointer, it allocates memory for the resource on the heap. The heap is a part of the program’s memory reserved for dynamic memory allocation.
When the unique pointer goes out of scope (e.g., a function exits or a block ends), the destructor of the pointed resource is called. This destructor, in turn, deletes the resource and releases the associated memory. This process happens automatically, even in case of exceptions, making unique pointers exceptionally safe and reliable.
Unique pointer functions to remember
Apart from the functions we've discussed in previous sections, here are a few other essential unique pointer functions you should be aware of:
reset
This function can be used to make a unique pointer point to a new resource or to release the current resource without destroying it.
In the above line of code, we are calling reset()
without a parameter, which sets the unique pointer to null
, and deletes the associated resource.
Here, we are passing an argument to the reset()
function. This code will replace the old pointed object with a new object.
release
The release
function is used to release ownership of the resource from the unique pointer, without destroying the resource.
In the above code, we are using the release()
call to take the ownership of the object from ptr
and transfer it to ptr2
. After this line is executed, ptr
will be null
.
It’s important to note that release()
doesn’t call the destructor for the pointed resource. Consider the following code:
releaseBadExample
std::unique_ptr<int> intPtr = std::make_unique<int>(42); intPtr.release(); //memory leak introduced here, dont do this.
Note
Above code will lead to a memory leak, as we have called
release()
but haven’t assigned the returned value to any variable.
operator* and operator->
These operators allow you to access the resource as if you're working directly with it. They provide a natural and intuitive way to interact with the managed object.
Obrigado pelo seu feedback!