2013-03-11 62 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); 
} 
相关问题