尝试引用已删除的函数时出错

时间:2016-02-06 21:27:39

标签: c++ vector reference

我想使用传递给初始化构造函数的参数初始化Enemy::copy,但是我收到以下错误:

C2280: 'Enemy &Enemy::operator =(const Enemy &)': attempting to reference a deleted function

以下是class Enemy的声明:

 #include "Pickup.h"
 class Enemy : public Entity
 {
 private:
        std::vector<Pickup>& copy;
 public:
        Enemy::Enemy(std::vector<Pickup>& arraypickup) : copy(arraypickup) {} 
 };

来自main()的代码:

std::vector<Pickup> arraypickup;
Enemy enemy(arraypickup);

我该如何解决?

1 个答案:

答案 0 :(得分:2)

这个答案是基于@Praetorian的正确建议。

修正案的简短回答:

问题出在std::vector<Pickup>& copy;类的Enemy成员中。将其更改为std::vector<Pickup> copy;,删除引用,以修复错误。实际上,完全没有必要将vector作为参考存储,相反,正如您所看到的,在类中引用成员会导致您遇到的错误。你可能会因为vector通过引用初始化c'tor而传递这一事实而感到困惑,但这绝不意味着你也应该让类成员成为引用。

如果您仍希望通过引用存储Enemy::copy数据,例如性能问题,考虑将其作为指针,如下所示:

class Enemy : public Entity
 {
 private:
        std::vector<Pickup>* copy;
 // rest of the class...
 };

答案很长:

重现问题的代码:

class Foo
{
    int& ri;
public:
//    default c'tor can't be defined in a sane fashion  because of the reference member ri
//    Foo() : ri(0) {}
    Foo(int& _ri) : ri(_ri) {}
};

int main(int argc, char **argv)
{
    int i{42};
    Foo f1{i};
    Foo f2{f1}; // we don't have a default constructor so using auto-generated copy c'tor
    f2 = f1; // <--- error
    return 0;
}

导致错误:

main.cpp: In function 'int main(int, char**)':
main.cpp:14:12: error: use of deleted function 'Foo& Foo::operator=(const Foo&)'
         f2 = f1; // <--- error
            ^
main.cpp:1:11: note: 'Foo& Foo::operator=(const Foo&)' is implicitly deleted
                     because the default definition would be ill-formed:
     class Foo
           ^
main.cpp:1:11: error: non-static reference member 'int& Foo::ri',
                      can't use default assignment operator

说明:

自动生成的operator=(),在这种情况下会生成[1],由于您无法重新分配参考,因此被视为ill-formed C ++ [2]。如果存在,则自动生成的operator=(Foo& other)将尝试执行this->ri = other.ri,这被认为是不正确的(编译器报告的“格式错误”),因为它是重新分配引用ri

最后,我建议查看[3],并就此问题进行深入解答。

  1. about auto-generated copy assignment operator

  2. about re-assigning references

  3. Assignment operator and copy constructor in the presence of references