Home >Backend Development >C++ >`make_shared` vs. `shared_ptr`: Why is One More Efficient and Exception-Safe?

`make_shared` vs. `shared_ptr`: Why is One More Efficient and Exception-Safe?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 12:19:11496browse

`make_shared` vs. `shared_ptr`: Why is One More Efficient and Exception-Safe?

Differences in make_shared and Standard shared_ptr

Why is make_shared more efficient?

To understand the efficiency of std::make_shared compared to a standard shared_ptr, let's examine their construction processes step by step.

Using the standard shared_ptr constructor:

std::shared_ptr<Object> p2(new Object("foo"));
  • Heap allocation for Object("foo") is performed.
  • New std::shared_ptr control block is created using the raw pointer.

Using std::make_shared:

std::shared_ptr<Object> p1 = std::make_shared<Object>("foo");
  • Single heap allocation for both std::shared_ptr control block and Object instance is performed.

Exception Safety

In the standard shared_ptr constructor approach, if an exception is thrown during the construction of Object, no cleanup is performed, leaving dangling memory. However, std::make_shared guarantees that the constructed Object and control block are part of a single allocation and will be cleaned up if an exception is thrown.

Disadvantage of std::make_shared

  • Increased memory retention compared to using the standard shared_ptr constructor: Since std::make_shared performs a single allocation, the pointed memory cannot be freed until the control block is no longer in use. Weak pointers to the object can keep the control block alive, potentially leading to extended memory retention.

The above is the detailed content of `make_shared` vs. `shared_ptr`: Why is One More Efficient and Exception-Safe?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn