Reputation: 5789
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
Reputation: 28872
Box2 - allocated on the stack
Advantages
Disadvatages
Box
for Box2 must be created when it is declared Box2
to another object without copying (or moving) all the data members individually.Box3 - allocated on the heap
Advantages
Box
well after you declare Box3
Disadvatages
Upvotes: 0
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