小编tru*_*ian的帖子

在C++中动态分配向量的安全方法是什么?

在动态分配struct之后,我认为在最后添加'delete'是谨慎的.但它给了我一个运行时错误.虽然编译好了.因此,如果我摆脱'删除',它运行正常.但我担心可能会有内存泄漏.处理此代码的安全方法是什么?

#include <iostream>
#include <vector>
using namespace std;

typedef struct
{
    vector<char*> vstr;
    vector<int> vint;

}VecStrInt;

int main()
{
    VecStrInt * mtx = new VecStrInt();

    mtx[0].vstr.push_back("Hello");
    mtx[0].vint.push_back(1);

    cout<<mtx[0].vint.at(0)<<endl;
    cout<<mtx[0].vstr.at(0)<<endl;

    //delete [] mtx;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ vector dynamic-allocation

2
推荐指数
1
解决办法
770
查看次数

标签 统计

c++ ×1

dynamic-allocation ×1

vector ×1