我正在尝试编译此代码,但是当编译器到达resize函数中的“ delete [] vector”(使用resize(5),而不是resize(10))时,出现异常,我不知道该怎么办正在发生。问题出在哪里,为什么此代码不起作用?以及如何改进程序以确保没有错误?
#pragma once
#include <stdlib.h>
#include <iostream>
#include <new>
using namespace std;
template<class T>
class Vector
{
public:
Vector() {
m_vector = nullptr;
m_nElements = 0;
}
~Vector() {
delete[] m_vector;
}
void resize(int tamany);
T& operator[](int indx);
int getNelements() { return m_nElements; }
Vector(const Vector &v);
Vector<T>& operator=(const Vector<T>& v);
private:
T* m_vector;
int m_nElements;
};
template<class T>
void Vector<T>::resize(int size) {
T* tmp;
tmp = new T[size];
for (int i = 0; i < m_nElements; i++) {
tmp[i] = m_vector[i];
}
if (m_vector != nullptr || m_nElements == 0) {
delete[] m_vector; //exception here!
}
m_vector = new T[size];
for (int i = 0; i < size; i++) {
m_vector[i] = tmp[i];
}
m_nElements = size;
}
template<class T>
T& Vector<T>::operator[](int indx) {
if (indx > m_nElements) {
cout << "Error, out of limits\n";
T tmp;
return tmp;
}
else {
return m_vector[indx];
}
}
template<class T>
Vector<T>::Vector(const Vector & v)
{
m_nElements = v.m_nElements;
if (v.m_vector != nullptr) {
m_vector = new T[m_nElements];
for (int i = 0; i < m_nElements; i++) {
m_vector[i] = v.m_vector[i];
}
}
}
template<class T>
inline Vector<T>& Vector<T>::operator=(const Vector<T>& v)
{
if (this != &v) {
m_nElements = v.m_nElements;
if (m_vector != nullptr) {
delete[] m_vector;
}
if (v.m_vector != nullptr) {
m_vector = new T[m_nElements];
for (int i = 0; i < m_nElements; i++) {
m_vector = v.m_vector;
}
}
else {
m_vector = nullptr;
}
}
return *this;
}
int main() {
Vector<int> v;
v.resize(10);
for (int i = 0; i < v.getNelements(); i++) {
v[i] = i;
}
v.resize(5);
for (int i = 0; i < v.getNelements(); i++) {
cout << v[i] << endl;
}
system("pause");
return 0;
}
答案 0 :(得分:2)
在void Vector<T>::resize(int size)
中,创建一个size
元素的数组:
T* tmp;
tmp = new T[size];
然后将m_nElements
个元素复制到其中:
for (int i = 0; i < m_nElements; i++) {
tmp[i] = m_vector[i];
}
因此,如果m_nElements
大于size
,则将写到数组末尾。
解决方案是复制m_nElements
或size
元素,以较小者为准。