Main Content

Use of new instead of make_unique

Use of new operator to initialize or reset unique_ptr

Since R2026a

Description

This defect occurs when you use the new operator instead of std::make_unique() to initialize or reset a unique_ptr from the standard library or Boost. For example, this code initializes a unique_ptr u_ptr2str by using the new operator.

std::unique_ptr<std::string> u_ptr2str(new std::string()); 
Polyspace® reports a defect.

Risk

Using the new operator provides no benefit over using std::make_unique().

Fix

To fix this defect, use std::make_unique() to initialize or reset unique_ptr objects. Using std::make_unique() avoids the drawbacks of the new operator..

Examples

expand all

In this example, a unique pointer widgetPtr is created by using new. Polyspace reports a defect.

#include <iostream>
#include <memory>

class Widget {
public:
    Widget() {
        std::cout << "Widget created\n";
    }
    ~Widget() {
        std::cout << "Widget destroyed\n";
    }
    void display() const {
        std::cout << "Displaying Widget\n";
    }
};

int main() {
    std::unique_ptr<Widget> widgetPtr(new Widget());
    widgetPtr->display();

    //...
    return 0;
}

Correction — use make_unique

To fix this defect, use make_unqiue when creating widgetPtr.

#include <iostream>
#include <memory>

class Widget {
public:
    Widget() {
        std::cout << "Widget created\n";
    }
    ~Widget() {
        std::cout << "Widget destroyed\n";
    }
    void display() const {
        std::cout << "Displaying Widget\n";
    }
};

int main() {
    auto widgetPtr = std::make_unique<Widget>();
    widgetPtr->display();

    // ...
    return 0;
}

Result Information

Group: Good Practice
Language: C++
Default: Off
Command-Line Syntax: MISSING_MAKE_UNIQUE
Impact: Low
PQL Name: std.defects.MISSING_MAKE_UNIQUE

Version History

Introduced in R2026a