向量中向量的push_back导致bad_alloc

时间:2019-04-01 12:30:30

标签: c++ bad-alloc

我正在处理一个大型项目,类似于newVec.push_back(vec[i]);的行会导致错误terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

但是,在一个最小化的示例中,我不能不能重现该错误,但是代码类似于以下内容:

#include<vector>
#include<iostream>

using namespace std;

class MyClass {
    public:
    vector<int> vec{1,2,3};
};

class MyClassTwo {
    public:
    vector<int> vec;
};

vector<int> doSometing(const vector<int> vec) {
        vector<int> newVec;
        for(int i = 0; i < vec.size(); i++) {
            newVec.push_back(vec[i]); //causes: terminate called after throwing an instance of 'std::bad_alloc' what():  std::bad_alloc
        }
        return newVec;
    }

int main() {
    MyClass c;
    MyClassTwo cTwo;

    cTwo.vec = doSometing(c.vec);

    cout << cTwo.vec[0] << endl;
}

有人知道我应该检查什么吗?

0 个答案:

没有答案