2013-03-11 42 views
0
/* Copy constructor */ 
List(const List<value_type>& list) 
{ 
    // for (iterator it = list.begin(); it != list.end(); ++it); 
    // this->push_back(*it); 
    // The commented part above is what I want it to do. 
    std::cout << "empty = " << this->empty(); // no seg fault; 
    std::cout << "size = " << this->size(); // also causes a seg fault 
    this->push_back("string") // causes a seg fault 
} 

試圖運行此代碼會給我的程序帶來seg錯誤。似乎每次我嘗試改變或改變(這)它只是拋出一個seg故障。爲什麼我的複製構造函數每次嘗試更改對象時都會產生段錯誤

而且它說(這)不是空的(這似乎是不拋出賽格故障的唯一一個)

這裏是要求進一步信息的方法的代碼。希望這裏有人能給我一些關於這裏發生的事情的見解。

void insert(iterator position, const value_type& in) 
{ 
    // If inserting at the front, just change the head to a new Node 
    if (position == this->head) 
     this->head = new Node<value_type>(in); 
    else 
    { 
     Node<value_type>* node = this->head; 
     // iterate to the position of "position". 
     for (; node->next != position.node; node = node->next); 
     node->next = new Node<value_type>(in); 
    } 
    // This is here to put back all the old data into it's correct position. 
    // I was having way too much with keeping the integrity of the data 
    // while inserting into the middle of the list, so I created this little hack. 
    for (iterator it = position; it != this->end(); ++it) 
    { 
      Node<value_type> *node = this->head; 
      for (; node->next != NULL; node = node->next); 
      node->next = new Node<value_type>(it.node->data); 
    } 
} 

// Insert at end 
void push_back(value_type in) 
{ 
    this->insert(this->end(), in); 
} 

unsigned size() 
{ 
    if (this->empty()) return 0; 
    unsigned i = 0; 
    for (iterator it = this->begin(); it != this->end(); ++it, ++i); 
    return i; 
} 

bool empty() const { return this->head == NULL; } 

回答

0

在我寫完這篇文章後,我幾乎立即想到了這個問題。

我所要做的就是先分配頭爲NULL

List(List<value_type>& list) 
{ 
    this->head = NULL; 

    for (iterator it = list.begin(); it != list.end(); ++it) 
     this->push_back(*it); 
} 
相關問題