簡體   English   中英

在C ++中操作向量時出現分段錯誤

[英]Segmentation fault when operating a vector in c++

我正在嘗試學習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 null的指針初始化_x 然后將另一個size有效的指針推入該指針。 然后, printAll嘗試取消引用這些空指針。

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

一般而言,您使用的new太多了。 向量沒有理由包含指針而不是對象,也沒有理由讓y是動態的而不是自動的。

您的問題出在您的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>以擺脫當前必須處理的所有指針。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM