繁体   English   中英

错误:使用已删除的 function 'std::unique_ptr<_Tp, _Dp>::unique_ptr

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

我试图从基本 class 指针的向量返回一个unique_ptr以应用polymorphism ,因为无法复制unique_ptr 有没有办法解决? 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];
}

您不能复制unique_ptr 这里有几个选项

返回一个常规指针

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

返回对 unique_ptr 的引用

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

很难说哪个是正确的(如果有的话),但它们都应该编译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM