[英]Vector constructor memory allocation for constant iterators, seg fault
I am having troubles figuring out how to allocate space for this constructor. 我在弄清楚如何为此构造函数分配空间时遇到了麻烦。 It is supposed to construct a Vector with elements from another Vector between start and end.
应该使用起点和终点之间的另一个Vector中的元素构造一个Vector。
template <class T> Vector<T>::Vector(const_iterator start, const_iterator finish)
{
array = new T[2 * capacity()];
for( ; start != finish; start++ ){
push_back(*start);
}
}
I have been trying to debug this, but cannot figure it out. 我一直在尝试调试它,但无法弄清楚。 push_back looks like so:
push_back看起来像这样:
template <class T> void Vector<T>::push_back(const T & val)
{
if (size() == capacity()) {
reserve (2 * capacity() + 1);
}
array[ theSize++ ] = val;
}
Which calls reserve.. 哪个电话保留..
template <class T> void Vector<T>::reserve(int newCapacity)
{
if (newCapacity < size()) {
return;
}
T * array_copy = array;
array = new T [newCapacity];
for (int i = 0; i < size(); i++) {
array[i] = array_copy[i];
}
theCapacity = newCapacity;
delete [] array_copy;
}
So, to narrow the question down: 因此,将问题缩小:
Why is the segmentation fault happening? 为什么发生分段错误?
You didn't initialize size()
and capacity()
in the constructor. 您没有在构造函数中初始化
size()
和capacity()
。 The push_back()
called in constructor may be affected by the randomly initialized values. 构造函数中调用的
push_back()
可能会受到随机初始化值的影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.