ManyQuestions
ManyQuestions

Reputation: 158

Use of unique_ptr with overloaded constructor

I have a question on how to use unique_ptr together with an overloaded constructor.

Here is my class definition:

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). It only accepts std::unique_ptr<circle> MyCircle. How can I initialize that pointer using my custom constructor?

Upvotes: 1

Views: 169

Answers (2)

Secundi
Secundi

Reputation: 1190

Please understand, what you are exactly trying to achieve here:

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

std::unique_ptr is a class template. 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. So the type this template requires should be circle solely.

For completeness to Jarod42's answer: Pre-C++14 approach:

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").

Upvotes: 1

Jarod42
Jarod42

Reputation: 217275

It should be

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

Upvotes: 2

Related Questions