In C++, make_unique
and make_shared
are factory functions provided by the standard library (available since C++14) to create smart pointers. They help in managing dynamic memory safely and efficiently. Below is an explanation and usage examples for both.
make_unique
is used to create an instance of a class wrapped in a std::unique_ptr
. A std::unique_ptr
is a smart pointer that owns a dynamically allocated object and ensures that there is only one owner at a time.
make_shared
is used to create an instance of a class wrapped in a std::shared_ptr
. A std::shared_ptr
allows multiple pointers to own the same object. It keeps track of how many shared pointers point to the same object, and the object is deleted when all shared pointers to it are destroyed.
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor called!" << std::endl; }
~MyClass() { std::cout << "MyClass destructor called!" << std::endl; }
};
int main() {
// Using make_unique
auto unique_ptr = std::make_unique<MyClass>();
// Using make_shared
auto shared_ptr = std::make_shared<MyClass>();
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?