#include <cassert>
#include <iostream>
using namespace std;
#include <initializer_list>
class IntArray {
unsigned mLength = 0;
int *mData = nullptr;
public:
IntArray(unsigned length) : mLength(length) { mData = new int[length]; }
~IntArray() { delete[] this->mData; }
IntArray(const std::initializer_list<int> &list) : IntArray(list.size()) {
int count = 0;
for (auto &e : list) {
mData[count] = e;
++count;
}
}
friend ostream &operator<<(ostream &os, IntArray &arr) {
for (unsigned i = 0; i < arr.mLength; ++i) {
os << arr.mData[i] << " ";
}
os << endl;
return os;
}
//=operator
IntArray &operator=(const std::initializer_list<int> &array) {
delete[] mData;
mLength = array.size();
if (mData != nullptr) {
// mData = new int[mLength+1];
cout << "mLength is " << mLength << endl;
mData = new int[mLength];
int i{};
for (auto &e : array) {
mData[i++] = e;
// There's a buffer overrun due to this line
// so i change
// mData = new int[mLength]; to mData = new int[mLength+1];
// Is this bad?
// Let me know if there's another better way.
}
} else {
mData = nullptr;
}
return *this;
}
};
int main() {
IntArray intArray = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << intArray << endl;
}
缓冲区溢出问题一直困扰着我。编码大师mData[i++] = e;因为这一行,缓冲区溢出了。它比数组的索引大,对吧?所以我把这一行改为emData = new int[mLength];转换为mData =新整数[mLength+1];这样不好吗?如果有更好的方法,请告诉我。编程太难了...你们都是天才?
1条答案
按热度按时间vwkv1x7d1#
您的代码在clang、gcc和msvc上运行完美。您所指的内容没有任何问题,但是,我想指出
IntArray &operator=(const std::initializer_list<int> &array);
中的一些内容,此方法的第一行是delete[] mData;
,如果mData
是nullptr
,则可能会导致一些未定义的行为,因此将其更改为if(mData) delete[] mData;
。else{}
语句不运行,因此我建议您将其更改为如下形式这是它的一个可能的实现