user189035
user189035

Reputation: 5789

Advantage of `make_unique` over plain constructor?

I am wondering whether there is any advantage in declaring Box with a smart pointer (as Box3 in the code below) over the (for me more classical) declaration by calling the constructor (as Box2 in the code below) or if the difference between these two constructions essentially a matter of subjective preferences.

#include <iostream>
#include <memory>

class Box{
    private:
        double length;
        double width;
        double height;
    public:
        Box(double lengthValue, double widthValue, double heightValue); 
        double volume() const;      
};
Box::Box(double lValue, double wValue, double hValue):
    length {lValue}, width {wValue}, height {hValue} {
}
double Box::volume() const {
    return length * width * height;
}
int main() {    
    Box Box2 {1.5,2.5,3.5};
    std::cout << Box2.volume() << std::endl;    
    auto Box3 = std::make_unique<Box>(1.5,2.5,3.5);
    std::cout << Box3->volume() << std::endl;   
    return 0;
}

Upvotes: 0

Views: 202

Answers (3)

doron
doron

Reputation: 28872

Box2 - allocated on the stack

Advantages

  • allocation is cheap (just decrement the stack pointer)

Disadvatages

  • the associated Box for Box2 must be created when it is declared
  • Stack memory is limited and your program will probably crash if you run out
  • You cannot move Box2 to another object without copying (or moving) all the data members individually.

Box3 - allocated on the heap

Advantages

  • you can catch out of memory conditions `catch (std::bad_alloc) and potentially deal with them without crashing
  • you can create your object Box well after you declare Box3
  • you can move your Box object without having to copy (or move) all the individual data members.

Disadvatages

  • Box3 is allocated on the heap which is a slow operation.

Upvotes: 0

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

Dynamic allocation is an expensive operation relative to other basic operations in C++, so you should avoid it where it's not required.

That is, one big difference is that the dynamic allocation is slow.

Another difference is what you can do with it. The dynamically allocated instance can be made to persist after the block where it was crated, by moving ownership. In contrast, the directly declared variable ceases to exist when execution leaves the block.

Upvotes: 8

SergeyA
SergeyA

Reputation: 62553

No advantages in provided code, only disadvantages.

Upvotes: -1

Related Questions