please tell me why memory is not allocated in the line CLNAME* tmp=new CLNAME[this->Capacity_Ram];
the second day I'm looking for a problem, I can not understand what the problem is. The task is to write self-written vectors
Code:
header:
#pragma once
#include <iostream>
#include <memory.h>
using namespace std;
template <class CLNAME>
class MyVector{
protected:
CLNAME* Array;
int Size_Ram = 0;
int Capacity_Ram = 5;
public:
MyVector();
MyVector(const MyVector<CLNAME> &other);
int Capacity();
int Size();
void PushBack(CLNAME item);
};
#include "MyVector.ipp"
ipp:
//Конструкторы
template <class CLNAME>
MyVector<CLNAME>::MyVector() {
this->Array = new CLNAME[this->Capacity_Ram];
}
template <class CLNAME>
MyVector<CLNAME>::MyVector(const MyVector<CLNAME> &other) {
this->Capacity_Ram=other.Capacity_Ram;
this->Size_Ram=other.Size_Ram;
Array = new CLNAME[other.Capacity_Ram];
for (int i=0;i<other.Size_Ram;i ){
this->Array[i]=other.Array[i];
}
}
//Методы
template <class CLNAME>
int MyVector<CLNAME>::Capacity(){
return(this->Capacity_Ram);
};
template <class CLNAME>
int MyVector<CLNAME>::Size(){
return(this->Size_Ram);
};
template <class CLNAME>
void MyVector<CLNAME>::PushBack(CLNAME item) {
if (this->Size_Ram==0){
Array = new CLNAME[this->Capacity_Ram];
this->Capacity_Ram=Capacity_Ram*2;
}
if(Size_Ram==Capacity_Ram){
this->Capacity_Ram=Capacity_Ram*2;
CLNAME* tmp=new CLNAME[this->Capacity_Ram];
for (int i=0;i<Size_Ram;i ){
tmp[i]=Array[i];
}
delete [] Array;
Array = tmp;
}
Array[Size_Ram]=item;
Size_Ram =1;
}
//template <class CLNAME>
//MyVector<CLNAME> MyVector<CLNAME>::operator=(MyVector<CLNAME> other) {
//if (*this == other){
//return *this
//}
//this->Size_Ram=other.Size;
//this->Capacity_Ram=other.Capacity;
//this->Array=other.Array;
//};
main:
#include <iostream>
#include "MyVector.h"
int main() {
MyVector<int> vectors;
int a=65;
cout<<vectors.Capacity()<<endl;
cout<<vectors.Size()<<endl;
for (int i=0;i<=10;i ) {
vectors.PushBack(i);
}
cout<<vectors.Size()<<endl;
cout<<vectors.Capacity()<<endl;
}
CodePudding user response:
In MyVector<CLNAME>::PushBack
if (this->Size_Ram==0){
Array = new CLNAME[this->Capacity_Ram]; // already done in constructor, leaks.
// sets capacity of 5
this->Capacity_Ram=Capacity_Ram*2; // advertises a capacity of 10, not 5.
}
makes 2 mistakes. 1) storage was already allocated in the constructor so this leaks the constructor's allocation and is unnecessary. 2) Array = new CLNAME[this->Capacity_Ram];
asks for an array of Capacity_Ram
elements and then resets the capacity to Capacity_Ram=Capacity_Ram*2;
ruining the if(Size_Ram==Capacity_Ram)
capacity tests later in the program and allowing out-of-bounds accesses.
Solution: Remove the entire first if
and block. The constructor did this already.
Side note: This class needs an assignment operator and a destructor to go along with the copy constructor.