2013-10-30 55 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>摆脱所有你必须应付此刻的指针。