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:
make_shared
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.
creating_shared_pointer
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.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme