[英]C++: calling member functions within constructor?
The following code raises a runtime error: 以下代码引发运行时错误:
#include <iostream>
#include <iterator>
#include <ext/slist>
class IntList : public __gnu_cxx::slist<int> {
public:
IntList() { tail_ = begin(); } // seems that there is a problem here
void append(const int node) { tail_ = insert_after(tail_, node); }
private:
iterator tail_;
};
int main() {
IntList list;
list.append(1);
list.append(2);
list.append(3);
for (IntList::iterator i = list.begin(); i != list.end(); ++i) {
std::cout << *i << " ";
}
return 0;
}
Seems that the problem is in the constructor IntList()
. 似乎问题出在构造函数
IntList()
。 Is it because it calls the member function begin()
? 是因为它调用成员函数
begin()
吗?
Looks like You are inserting after end(); 看起来像是在end()之后插入;
In the body of the constructor 在构造函数的主体中
IntList() { tail_ = begin(); }
the base class is constructed and it's members can be called, but for an empty list, it should return end(); 构造基类并且可以调用它的成员,但是对于空列表,它应该返回end();
Your problem is not in the constructor but in the first call to append()
. 你的问题不是在构造函数中,而是在第一次调用
append()
。 Because your list is empty begin()
equals end()
. 因为你的列表是空的,所以
begin()
等于end()
。 end()
is a valid iterator, but the one after that isn't. end()
是一个有效的迭代器,但之后的那个不是。 To solve that particular problem try calling insert()
instead. 要解决该特定问题,请尝试调用
insert()
。
That said, a fast peek at <ext/slist>
confirms that the destructor of slist
isn't virtual, which means slist
wasn't intended to be derived from. 在这就是说,一个快速偷看
<ext/slist>
确认的析构函数slist
不是虚拟的,这意味着slist
不旨在被源自。
The documentation for slist<> indicates that the iterator provided to insert_after must be dereferenceable. slist <>的文档表明提供给insert_after的迭代器必须是可解除引用的。
Since your list is empty the begin() returns end() and is thus not dereferenceable. 由于您的列表为空,因此begin()返回end(),因此不能解除引用。
See documentation here: 请参阅此处的文档
http://www.sgi.com/tech/stl/Slist.html
iterator insert_after(iterator pos, const value_type& x)
iterator insert_after(iterator pos,const value_type&x)
pos must be a dereferenceable iterator in *this.
pos必须是* this中的可解除引用的迭代器。 (That is, pos may not be end().) Inserts a copy of x immediately following pos.
(也就是说,pos可能不是end()。)在pos之后立即插入x的副本。 The return value is an iterator that points to the new element.
返回值是指向新元素的迭代器。 Complexity: constant time.
复杂性:恒定时间。
如果集合中没有元素,则.begin()无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.