试图找到已删除的功能

在C ++中因类出现问题,遇到一个错误,指出我正在尝试引用已删除的函数。这是错误

  

C2280(Test&Test :: operator =(const Test&:试图引用已删除的函数)。

这是我的代码:

#include "pch.h"
#include <iostream>

using namespace std;

class Test {
public:
    int size;
    double* array;
public: 
    Test();
    Test& operator=(Test&& a);
    Test(int sizeArg) {
        size = sizeArg;
        array = new double[size];
    }
    Test(Test&& arg) {
        size = arg.size;
        array = arg.array;
        arg.size = 0;
        arg.array = nullptr;
    }
    ~Test()
    {
        if (array != nullptr) {
            delete[]array;
        }
    }
};

int main()
{
    Test outTest;
    int x = 1;
    //Wont work since looking for a deleted function
    if (x = 1) {
        Test arg(200000000);
        outTest = arg;
    }
    cout << outTest.array;
}

问题出在main()等号上。

yinguang120 回答:试图找到已删除的功能

您应该会在以下方面出现错误:

  

constexpr Test& Test::operator=(const Test&)’ is implicitly declared as deleted because ‘Test’ declares a move constructor or move assignment operator

这是一件好事,因为默认的副本分配运算符会做得很糟糕。它将复制您的指针-并且您将最终获得两个都声称拥有数据的实例。两者都将稍后尝试delete[]-结果是未定义的行为。

您可能应该实现The rule of three/five/zero中提到的所有5个成员函数。

示例:

#include <algorithm>
#include <iostream>
#include <utility>

class Test {
public:
    int size;
    double* array;
public: 
    Test() : 
        size(0),array(nullptr)                    // make sure the default constructed array
                                          // is set to nullptr
    {}
    Test(int sizeArg) :
        size(sizeArg),array(new double[size]{})         // zero initialize the array
    {}
    // rule of five:
    Test(const Test& arg) :               // copy ctor
        size(arg.size),array(new double[size])
    {
        std::copy(arg.array,arg.array+size,array);
    }
    Test(Test&& arg) :                    // move ctor
        size(arg.size),array(std::exchange(arg.array,nullptr)) // get pointer from arg and give nullptr
                                                 // to arg
    {}
    Test& operator=(const Test& arg) {    // copy assignment operator
        Test tmp(arg);                    // reuse copy constructor
        std::swap(*this,tmp);            // let "tmp" destroy our current array
        return *this;
    } 
    Test& operator=(Test&& arg) {         // move assignment operator 
        size = arg.size;
        std::swap(array,arg.array);      // let the other object delete our current array
        return *this;
    }   
    ~Test() {
        delete[] array;                   // no "if" needed,it's ok to delete nullptr
    }
};

int main()
{
    Test outTest;
    int x = 1;

    if(x==1) {                           // use == when comparing for equality
        Test arg(2);
        outTest = arg;
    }
    std::cout << outTest.array;
}
本文链接:https://www.f2er.com/2974295.html

大家都在问