Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Inner Workings of a Unique Pointer | Unique Pointers
C++ Smart Pointers
course content

Conteúdo do Curso

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. References
6. Advanced topics

bookInner 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:

cpp

releaseBadExample

copy
12
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.

What does the reset() function do when called without a parameter?

What does the reset() function do when called without a parameter?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 5
We're sorry to hear that something went wrong. What happened?
some-alt