【发布时间】:2015-10-02 00:35:30
【问题描述】:
我正在编写以下数组(类),当这个数组的索引大于这个数组的大小时,它会增加大小。 我知道向量,但它必须是数组。代码如下所示:
#include <iostream>
using namespace std;
class Array {
public:
Array():_array(new float[0]), _size(0){};
~Array() {delete[] _array;}
friend ostream &operator<<(ostream&,const Array&);
float& operator[] (int index)
{
if(index>=_size)
{
float* NewArray=new float[index+1];
for(int i=0;i<_size;++i) NewArray[i]=_array[i];
for(int i=_size;i<index+1;++i) NewArray[i]=0;
delete[] _array;
_array=NewArray;
_size=index+1;
}
return _array[index];
}
private:
float *_array; // pointer to array
int _size; // current size of array
};
ostream &operator << ( ostream &out, const Array& obj) // overloading operator<< to easily print array
{
cout << "Array:\n\n";
for (int i=0;i<obj._size;++i)
{
cout << obj._array[i];
if(i+1!=obj._size) cout << ", ";
}
cout << ".\n";
return out;
}
int main()
{
Array CustomArray;
CustomArray[2] = CustomArray[1] = CustomArray[0] = 3.14; // **here is the problem**
cout << CustomArray << endl;
}
一切正常,0 个警告,0 个 valgrind 错误,输出:
3.14, 3.14, 3.14.
但是我必须以这种方式编写这段代码(在 main 中):
CustomArray[0] = CustomArray[1] = CustomArray[2] = 3.14;
现在是 3 个 valgrind 错误: 地址(some_address)是大小为 8 的块内的 4 个字节,
输出看起来像这样:0, 0, 3.14.
不幸的是,我必须编写此代码才能以第二种方式工作
(CustomArray[0] = CustomArray[1] = CustomArray[2] = 3.14;)
你们能帮忙吗?提前致谢
【问题讨论】:
-
问题是
CustomArray[1]使所有先前的引用和指向数据的指针无效,因为它被重新分配了。你可以做的是返回一个ArrayAccess,它保存索引并且不保存引用但每次都访问原始数组。 -
嗯,如果其中一个
operator[]调用导致重新分配,我认为即使std::vector也无法应对......
标签: c++ arrays class memory-management operator-overloading