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

bookCreating 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.h

make_shared.h

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.

creating_shared_pointer.h

creating_shared_pointer.h

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt