Box
のスマートポインタ(以下のコードではBox3
)をコンストラクタ(以下のコードではBox2
)の呼び出しによって、またはこれら2つの構成の間には本質的に主観的好みの問題がある。`make_unique`をプレーンコンストラクタよりも優れていますか?
#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;
}
ポインタを使用しても、ポインタを使用しない場合に比べて「利点」があるわけではありません。ポインターが必要な場合があります*。ダイナミックメモリ割り当てが必要な場合もあります*。あなたがそれらを必要としない場合、それらを「ただのために」使用しないでください。 –