Shared Pointer Creation: new vs make_shared
Question 6 / 17 • Correct so far: 0 (0 answered)
New Shared Ptr
std::shared_ptr<Widget> createWidget(int id, double value, const std::string& name) {
return std::shared_ptr<Widget>(new Widget(id, value, name));
}
auto ptr = createWidget(WIDGET_ID, WIDGET_VALUE, WIDGET_NAME); Make Shared Ptr
std::shared_ptr<Widget> createWidget(int id, double value, const std::string& name) {
return std::make_shared<Widget>(id, value, name);
}
auto ptr = createWidget(WIDGET_ID, WIDGET_VALUE, WIDGET_NAME); Shared test data (shared-setup)
struct Widget {
int id;
double value;
std::string name;
Widget(int id, double value, std::string name)
: id(id), value(value), name(std::move(name)) {}
};
const int WIDGET_ID = 42;
const double WIDGET_VALUE = 3.14;
const std::string WIDGET_NAME = "benchmark-widget"; Which snippet is faster?
Snippet B is faster. std::make_shared performs a single heap allocation
for both the managed object and the reference-counting control block.
Using new with the std::shared_ptr constructor requires two separate
allocations — one for the object and one for the control block — doubling
allocation overhead and increasing pressure on the memory allocator.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Make Shared Ptr | 18.9 ns | 1.4× |
| New Shared Ptr | 26.1 ns | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.