试图找到已删除的函数

Trying to locate a deleted function

在 C++ 中为 class 搞乱并遇到一个错误,指出我正在尝试引用已删除的函数。这是错误

C2280(Test &Test::operator = (const Test& : attempting to reference a deleted function).

这是我的代码:

#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()等号上

您应该会收到以下几行错误:

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;
}