2013-10-30 56 views
1

我正在嘗試學習C++,並且我想用一個簡單的程序來初始化一個X實例的向量作爲類成員,但是我遇到了分段錯誤......你能幫忙嗎?在C++中操作矢量時出現分段錯誤

#include <iostream> 
#include <vector> 

class X { 
    int _x; 
    public: 
    X(int i) { _x = i; } 
    void print() { std::cout << this->_x << std::endl; } 
    void xAdd() { _x++; } 
}; 


class Y { 
    std::vector<X*> _x; 
    public: 
    Y(int size) : _x(size) { 
     for (int i = 0; i < size; ++i) _x.push_back(new X(1)); 
    } 
    void printAll() { 
     for(unsigned int i = 0; i < _x.size()-1; i++) { 
     _x[i]->print(); 
     } 
    } 
}; 

int main(){ 
    Y *y = new Y(5); 
    y->printAll(); 
    return 0; 
} 
+0

您的課程旨在泄漏記憶。所有由'_X'元素指向的對象都需要手動釋放。爲了避免這種情況,請使用智能指針(或者根本不要使用指針)。 –

回答

1

您有2個內存泄漏。除非必須,否則不要使用new

當您不需要時,您正在使用循環進行初始化。

您可以設置矢量的初始大小(以及初始值),然後執行push_back。因此,第一個N值是默認構造的(和NULL)。

您的printAll函數將打印除最後一個元素以外的所有元素。

class X 
{ 
private: 
    int _x; 
public: 
    X(int i) { _x = i; } 
    void print() { std::cout << _x << std::endl; } // this-> is not needed 
    void xAdd() { _x++; } 
}; 

class Y 
{ 
private: 
    std::vector<X> _x; // no need to store pointers, store the object itself 
public: 
    Y(int size) : _x(size, X(1)) // use the fill version of the constructor 
    { } 

    // simple way to print (there are other ways to do the same thing) 
    void printAll() 
    { 
     std::for_each(_x.begin(), _x.end(), [](const X& x) 
     { 
      x.print(); 
     }); 
    } 
}; 

int main() 
{ 
    Y y(5); // no need for heap allocation 
    y.printAll(); 
    return 0; 
} 
4

您初始化爲_xsize空指針;那麼你可以將另一個size有效指針推到它上面。然後printAll試圖取消引用這些空指針。

刪除初始化程序(可能會添加_x.reserve(size);以最小化分配);或者將環路體更改爲_x[i] = new X(1);

作爲一般說明,您使用的太多太多了,請使用new。沒有任何理由讓矢量包含指針而不是對象,或者爲了動態而不是自動的。

1

你的問題是在你的Y類的構造函數:

class Y { 
    std::vector<X*> _x; 
    public: 
    Y(int size) : _x(size) { // initializing the vector with size elements all set to nullptr 
     for (int i = 0; i < size; ++i) _x.push_back(new X(1)); // pushing back size pointers to actual instances of X 
    } 
    void printAll() { 
     for(unsigned int i = 0; i < _x.size()-1; i++) { // iterating over the first size items of the vector which are the nullptrs and derefencing them. 
     _x[i]->print(); 
     } 
    } 
}; 

你應該考慮使其成爲一個std::vector<X>擺脫所有你必須應付此刻的指針。