【问题标题】:Use of unique_ptr with overloaded constructor使用带有重载构造函数的 unique_ptr
【发布时间】:2021-02-19 12:00:12
【问题描述】:

我有一个关于如何将unique_ptr 与重载构造函数一起使用的问题。

这是我的类定义:

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;
};

这就是我想要创建指针的方式:

std::unique_ptr<circle(radius1, center1)> myCircle;

但是,我的编译器(MS VisualStudio 2019)不接受它。它只接受std::unique_ptr&lt;circle&gt; MyCircle。如何使用自定义构造函数初始化该指针?

【问题讨论】:

  • 你是在创建指针还是在创建一个圆圈?
  • 在 C++14 之前。 std::unique_ptr&lt;circle&gt; MyCircle(new circle(radius1, centre1))。 C++14 及更高版本:std::unique_ptr&lt;circle&gt; MyCircle = std::make_unique&lt;circle&gt;(radius1, centre1)

标签: c++ pointers unique-ptr


【解决方案1】:

应该是

auto /* std::unique_ptr<circle> */ myCircle = std::make_unique<circle>(radius1, center1);

【讨论】:

  • 顺便说一句:汽车在做什么?
  • auto 进行自动类型推断。所以编译器从表达式std::make_unique&lt;circle&gt;(radius1, center1) 的类型推导出myCircle 的类型。在这种情况下,该类型将是 std::unique_ptr&lt;circle&gt;
【解决方案2】:

请理解,您究竟想在这里实现什么:

std::unique_ptr<circle(radius1, center1)> myCircle;

std::unique_ptr 是一个类模板。您提供的模板参数必须是一个类型(通常不是完整的事实,但在这里),而不是一个类型的实例!但是你正试图传递你班级圈子的一个实例(一个临时的)。所以这个模板需要的类型应该是唯一的圆形。

为了完整的 Jarod42 的回答:Pre-C++14 方法:

std::unique_ptr<circle> myCircle = std::unique_ptr<circle>(new circle(radius1, center1));

虽然这种旧语法在异常安全方面比通过 make_unique 推荐的方法弱,但它更明确地说明了正在发生的事情(堆分配、构造函数调用“位置”)。

【讨论】:

  • 在 pre-c++14 中(所以在 C++11 中),我会自己做 make_unique :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 2022-01-17
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多