Mohamed Atef
Mohamed Atef

Reputation: 13

error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr

I am trying to return a unique_ptr from a vector of base class pointers to apply polymorphism as unique_ptr can not be copied. Is there any way around this? See he function.

#include <bits/stdc++.h>

using namespace std;

class shape {
public:
  virtual void foo() = 0;
};

class circle : public shape {
public:
  virtual void foo() override {cout << "I am circle" << endl;}
};

class square : public shape {
public:
  virtual void foo() override {cout << "I am square" << endl;}
};

unique_ptr<shape> da(int x) {
  if(x)
    return make_unique<circle>();
  return make_unique<square>();
}

unique_ptr<shape> he(const vector<unique_ptr<shape>> &t, int x) {
  return t[x];
}

Upvotes: 0

Views: 210

Answers (1)

john
john

Reputation: 87944

You cannot copy a unique_ptr. Here's a couple of options

Return a regular pointer

shape* he(const vector<unique_ptr<shape>> &t, int x) {
  return t[x].get();
}

Return a reference to the unique_ptr

const unique_ptr<shape>& he(const vector<unique_ptr<shape>> &t, int x) {
  return t[x];
}

Hard to say which is right (if any), but they should both compile.

Upvotes: 2

Related Questions