Looks like std::make_unique is making extra copy(related post) while it is supposed to be more efficient. Below is a sample implementation with typical c++ polymorphic class architecture. The output mentioned below the code snippet shows if we uncomment the call to make_unique, it calls an extra pair of ctor/dtor.
class Shape
{
public:
Shape() { cout << "Shape::ctor\n"; }
virtual ~Shape() {cout << "Shape::dtor\n";}
};
class Rectangle : public Shape
{
public:
Rectangle() {cout << "Rectangle::ctor\n";}
virtual ~Rectangle() {cout << "Rectangle::dtor\n";}
};
unique_ptr<Shape> makeShape(int type)
{
//unique_ptr<Shape> spShape = make_unique<Shape>(); //extra ctor call
unique_ptr<Shape> spShape(nullptr);
switch (type)
{
case 1: //rect
spShape.reset(new Rectangle());
break;
default:
break;
}
return spShape;
}
int main(int argc, char const *argv[])
{
auto shape1 = makeShape(1);
return 0;
}
========================== output with make_unique -------------------------- Shape::ctor Shape::ctor Rectangle::ctor Shape::dtor Rectangle::dtor Shape::dtor -------------------------- output w/o make_unique -------------------------- Shape::ctor Rectangle::ctor Rectangle::dtor Shape::dtor --------------------------
make_unique doesn't works with custom deleter. So what is benefit of using it?