Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Creating and Sharing Shared Pointers | Shared Pointers
C++ Smart Pointers
course content

Cursusinhoud

C++ Smart Pointers

C++ Smart Pointers

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

book
Creating and Sharing Shared Pointers

The Recommended Approach

The recommended way to create a shared pointer is through the std::make_shared function. This approach is generally more efficient and expressive compared to using new. It allocates memory for the object and the control block (reference count) in a single step. For example:

h

make_shared

copy
12
// Create a shared pointer to an integer std::shared_ptr<int> p_int = std::make_shared<int>(42);

The above line allocates a dynamic integer and also initializes a shared pointer to it with a reference count of one.

The Discouraged Approach

You can also create shared pointers using new, but this method is discouraged because it is neither expressive nor efficient. The syntax for this approach requires you to pass the object to the shared pointer constructor.

h

creating_shared_pointer

copy
12
// Also creates a shared pointer to an integer std::shared_ptr<int> p_int(new int(42));

Allocating a dynamic integer and then passing it to the constructor of the shared pointer. However, the control block (reference count) will get initialized inside the constructor.

This means that we are doing two separate initializations, which is inefficient and error could be generated.

Passing Around Shared Pointers

Shared pointers are purpose-built for safe sharing. Let's explore a few ways we can pass them around.

question mark

If four shared_ptr instances share ownership of the same dynamic object, when will the object's destructor be called?

Select the correct answer

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 2
Onze excuses dat er iets mis is gegaan. Wat is er gebeurd?
some-alt