Junior — Middle
What are the advantages and disadvantages of using the make_unique function in C++?
sobes.tech AI
Answer from AI
The make_unique function in C++ creates an object in dynamic memory and returns a std::unique_ptr smart pointer to that object.
Advantages:
- Safe memory management: prevents memory leaks, as
unique_ptrautomatically deletes the object. - Convenience: no need to explicitly write
newanddelete. - Prevents errors with exceptions: the object is created and immediately wrapped in a
unique_ptr, which prevents leaks if an exception is thrown.
Disadvantages:
- Requires C++14 support or higher (not available in C++11 standard).
- Slightly more overhead compared to raw pointers, but justified by safety.
Example usage:
#include <memory>
struct MyClass {
int value;
MyClass(int v) : value(v) {}
};
int main() {
auto ptr = std::make_unique<MyClass>(42);
// ptr will automatically free memory when it goes out of scope
}