在 c++ 中操作向量时的分割错误

Segmentation fault when operating a vector in c++

本文关键字:分割 错误 向量 c++ 操作      更新时间:2023-10-16

我正在尝试学习 c++,我想用一个简单的程序将 X 实例的向量初始化为类成员,但我遇到了分段错误......你能帮忙吗?

#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;
}

你用size空指针初始化_x;然后你把另一个size有效的指针推到它上面。然后printAll尝试取消引用这些空指针。

删除初始化器(可能添加_x.reserve(size);以最小化分配);或者将循环体更改为_x[i] = new X(1);

作为一般说明,你使用new太多了。矢量没有理由包含指针而不是对象,也没有理由让y是动态的而不是自动的。

您有 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;
}

你的问题出在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>来摆脱您目前必须处理的所有指针。