C++ c++;在copy-ctor的帮助下重载=运算符

C++ c++;在copy-ctor的帮助下重载=运算符,c++,C++,我构造了一个名为buffer的简单容器。当重载=运算符时,我得到以下错误 在init_list_test.exe中的0x774AEBA5(ntdll.dll)处引发异常: 0xC000000D:传递给服务或函数的参数无效。 init_list_test.exe中0x774AEBA5(ntdll.dll)处未处理的异常: 0xC000000D:传递给服务或函数的参数无效 我不太清楚这意味着什么 下面是要复制的代码: #include "buffer.h" int main() { buff

我构造了一个名为buffer的简单容器。当重载=运算符时,我得到以下错误

在init_list_test.exe中的0x774AEBA5(ntdll.dll)处引发异常: 0xC000000D:传递给服务或函数的参数无效。 init_list_test.exe中0x774AEBA5(ntdll.dll)处未处理的异常: 0xC000000D:传递给服务或函数的参数无效

我不太清楚这意味着什么

下面是要复制的代码:

#include "buffer.h"
int main()
{
    buffer buf(10);
    buffer test(10);
    buf = test;


    return 0;
}
在buffer.cpp中

#include "buffer.h"
#include <iostream>
size_t buffer::get_size() const
{
    return length;
}
buffer::buffer(size_t length) : start(new int[length]), length(length)
{
    std::cout << length << +" size" << std::endl;
}

buffer::buffer(const buffer& rhs) : start(new int[length]), length(rhs.get_size())
{
    std::copy(rhs.begin(), rhs.end(), start);
}

buffer& buffer::operator=(const buffer& rhs)
{
    buffer temp_buff(rhs);
    return temp_buff;

}

int* buffer::begin()
{
    return start;
}

int* buffer::end()
{
    return start + length;
}

const int* buffer::begin() const
{
    return start;
}

const int* buffer::end() const
{
    return start + length;
}
我在cppref上看到,官方方法是执行以下代码:

// assume the object holds reusable storage, such as a heap-allocated buffer mArray
T& operator=(const T& other) // copy assignment
{
    if (this != &other) { // self-assignment check expected
        if (other.size != size) {         // storage cannot be reused
            delete[] mArray;              // destroy storage in this
            size = 0;
            mArray = nullptr;             // preserve invariants in case next line throws
            mArray = new int[other.size]; // create storage in this
            size = other.size;
        } 
        std::copy(other.mArray, other.mArray + other.size, mArray);
    }
    return *this;
}

但是,我想使用我已经设计的复制选择器,因为代码非常相似。

您的赋值运算符不会修改此
。它实际上不做任何作业。那应该是个危险信号。好吧,也许我在这里有点慢。但是为什么它需要修改这个呢?为什么我不能返回temp_buff而不是这个?@0x5453哦,问题是我可以使用rhs.size()作为缓冲区的长度?我懂了。你有什么链接可以让我读到吗?好吧,如果我给一个int赋值5,我希望int的值是5。如果赋值没有改变它的值,它怎么能保持一个新的值呢?但是我想使用我已经设计好的复制向量,因为代码非常相似。这听起来像是你在找那个。
// assume the object holds reusable storage, such as a heap-allocated buffer mArray
T& operator=(const T& other) // copy assignment
{
    if (this != &other) { // self-assignment check expected
        if (other.size != size) {         // storage cannot be reused
            delete[] mArray;              // destroy storage in this
            size = 0;
            mArray = nullptr;             // preserve invariants in case next line throws
            mArray = new int[other.size]; // create storage in this
            size = other.size;
        } 
        std::copy(other.mArray, other.mArray + other.size, mArray);
    }
    return *this;
}