I tried to define a Vector class and some functions of it manually. Everything seemed like okay, until I wrote the copy constructor, where I get a warning in this part of the loop:
this->arr[i] = vec.arr[i];
C6386:Buffer overrun while writing to 'this->arr'
#include <iostream>
using namespace std;
class Vector {
private:
int size, capacity;
int* arr;
public:
Vector(int _capacity = 5) : capacity(_capacity) {
size = 0;
arr = new int[capacity];
cout << "constructor" << endl;
}
~Vector() {
delete[] arr;
cout << "destructor" << endl;
}
Vector(const Vector& vec) {
this->capacity = vec.capacity;
this->size = vec.size;
this->arr = new int[this->capacity];
for (int i = 0; i < size; ++i) {
this->arr[i] = vec.arr[i]; //WARNING. C6386:Buffer overrun while writing to 'this->arr'
}
cout << "copy constructor" << endl;
}
void push_back(int n) {
if (size==capacity) {
resize();
}
arr[size] = n;
size++;
}
void resize() {
int* tmp = new int[capacity*=2];
for (int i = 0; i < size; ++i) {
tmp[i] = arr[i];
}
delete[] arr;
arr = tmp;
}
int Size() { return size; }
};
int main() {
Vector V1(3);
V1.push_back(1);
cout << V1.Size();
V1.push_back(4);
cout << V1.Size() << endl;
V1.push_back(4);
cout << V1.Size() << endl;
V1.push_back(4);
cout << V1.Size() << endl;
Vector V2(V1);
return 0;
}
I thought the problem is that I'm not careful enough and I maybe let the loop get out of the bounds somewhere, but it seems like that is okay.
Can you please help me to define the problem?
Vectoruser-defined assignment operator. Thus any code that uses your class that makes copies ofVectorwill be flawed. What is the rule of 3?size <= capacity.