[英]C++: calling member functions within constructor?
以下代碼引發運行時錯誤:
#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;
}
似乎問題出在構造函數IntList()
。 是因為它調用成員函數begin()
嗎?
看起來像是在end()之后插入;
在構造函數的主體中
IntList() { tail_ = begin(); }
構造基類並且可以調用它的成員,但是對於空列表,它應該返回end();
你的問題不是在構造函數中,而是在第一次調用append()
。 因為你的列表是空的,所以begin()
等於end()
。 end()
是一個有效的迭代器,但之后的那個不是。 要解決該特定問題,請嘗試調用insert()
。
在這就是說,一個快速偷看<ext/slist>
確認的析構函數slist
不是虛擬的,這意味着slist
不旨在被源自。
slist <>的文檔表明提供給insert_after的迭代器必須是可解除引用的。
由於您的列表為空,因此begin()返回end(),因此不能解除引用。
請參閱此處的文檔
http://www.sgi.com/tech/stl/Slist.html
iterator insert_after(iterator pos,const value_type&x)
pos必須是* this中的可解除引用的迭代器。 (也就是說,pos可能不是end()。)在pos之后立即插入x的副本。 返回值是指向新元素的迭代器。 復雜性:恆定時間。
如果集合中沒有元素,則.begin()無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.