Home >Backend Development >C++ >`std::make_shared` vs. `std::shared_ptr`: Which is More Efficient?

`std::make_shared` vs. `std::shared_ptr`: Which is More Efficient?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 02:04:10647browse

`std::make_shared` vs. `std::shared_ptr`: Which is More Efficient?

Discerning the Efficiency of std::make_shared vs. Direct std::shared_ptr Usage

Understanding the difference in efficiency between std::make_shared and directly constructing a std::shared_ptr can be a perplexing task. Here, we delve into a detailed comparison to elucidate the intricacies of each method.

Exploring the Construction Sequence

Consider the following code snippets:

std::shared_ptr<Object> p1 = std::make_shared<Object>("foo");
std::shared_ptr<Object> p2(new Object("foo"));

Direct std::shared_ptr Construction:

  1. Heap allocation for Object
  2. Shared pointer constructor, allocating another heap region for metadata

std::make_shared Usage:

  1. Combined heap allocation, encompassing both Object and metadata

Unmasking the Efficiency Gain

The key difference lies in the number of heap allocations required:

  • make_shared: 1 allocation
  • Direct shared_ptr: 2 allocations

This singular allocation in make_shared eliminates the need for an explicit new call, resulting in increased efficiency.

Exception Considerations

Pre-C 17:
Exception handling could previously wreak havoc, as the raw pointer might not have been safely passed to the shared_ptr constructor.

C 17 and Later:
This issue has been resolved thanks to changes in function argument evaluation order. Today, exceptions are handled gracefully, ensuring memory integrity.

A Minor Drawback of std::make_shared

As Casey pointed out, a potential disadvantage stems from the single allocation:

  • The controlled memory cannot be released until the control block is no longer in use, potentially prolonging memory retention due to weak pointer references.

The above is the detailed content of `std::make_shared` vs. `std::shared_ptr`: Which is More Efficient?. 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
Previous article:How Can I Overload theNext article:How Can I Overload the