I'm constructed a simple container called buffer. When overloading the = operator i'm getting the following error
Exception thrown at 0x774AEBA5 (ntdll.dll) in init_list_test.exe: 0xC000000D: An invalid parameter was passed to a service or function. Unhandled exception at 0x774AEBA5 (ntdll.dll) in init_list_test.exe: 0xC000000D: An invalid parameter was passed to a service or function.
Not really sure what this means.
Here is the code to reproduce:
#include "buffer.h"
int main()
{
buffer buf(10);
buffer test(10);
buf = test;
return 0;
}
in 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;
}
in buffer.h
#pragma once
class buffer {
int* start;
size_t length;
public:
size_t get_size() const;
explicit buffer(size_t size);
buffer(const buffer& rhs);
buffer& operator=(const buffer& rhs);
int* begin();
int* end();
const int* begin() const;
const int* end() const;
};
I saw on cppref that the offical way was to do something like this code below:
// 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;
}
However i wanted to use the copy ctor that i already designed since the code is very similar.