[英]Use of unique_ptr with overloaded constructor
I have a question on how to use unique_ptr
together with an overloaded constructor.我有一个关于如何将
unique_ptr
与重载构造函数一起使用的问题。
Here is my class definition:这是我的 class 定义:
class circle : public segment
{
public:
circle()
{
center.x = 0;
center.y = 0;
};
circle(const double r, const point c)
{
radius = r;
center.x = c.x;
center.y = c.y;
segment_id = 2;
};
~circle() {};
double get_radius() { return radius; };
point get_center() { return center; };
double get_length() { return 3.14 * radius; }; //returns circumference
private:
double radius = 0;
point center;
};
And this is how I would like to create the pointer:这就是我想创建指针的方式:
std::unique_ptr<circle(radius1, center1)> myCircle;
However, it is not accepted by my compiler (MS VisualStudio 2019).但是,我的编译器(MS VisualStudio 2019)不接受它。 It only accepts
std::unique_ptr<circle> MyCircle
.它只接受
std::unique_ptr<circle> MyCircle
。 How can I initialize that pointer using my custom constructor?如何使用我的自定义构造函数初始化该指针?
It should be它应该是
auto /* std::unique_ptr<circle> */ myCircle = std::make_unique<circle>(radius1, center1);
Please understand, what you are exactly trying to achieve here:请理解,您究竟想在这里实现什么:
std::unique_ptr<circle(radius1, center1)> myCircle;
std::unique_ptr is a class template. std::unique_ptr 是一个 class 模板。 The template argument you are providing must be a type (not the full truth in general, but here it is), not an instance of a type.
您提供的模板参数必须是一个类型(通常不是完整的事实,但在这里),而不是一个类型的实例。 But you're trying to pass an instance (a temporary) of your class circle.
但是您正在尝试传递您的 class 圈子的实例(临时)。 So the type this template requires should be circle solely.
所以这个模板需要的类型应该是唯一的圆形。
For completeness to Jarod42's answer: Pre-C++14 approach:为了完整 Jarod42 的回答:Pre-C++14 方法:
std::unique_ptr<circle> myCircle = std::unique_ptr<circle>(new circle(radius1, center1));
Although this old syntax is weaker than the recommended approach via make_unique in terms of exception safety, it's more explicit about what's going on (heap allocation, constructor call "position").尽管这种旧语法在异常安全方面比通过 make_unique 推荐的方法弱,但它更明确地说明了正在发生的事情(堆分配、构造函数调用“位置”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.