首页 > 解决方案 > 这个 c++ 向量初始化会导致内存泄漏吗?

问题描述

我有以下代码:

#include <iostream>
#include <vector>

class Test
{
public:
    int first;
    int second;

    Test(int a, int b)
    {
        first = a;
        second = b;
    }
};

int main(int argc, char* argv[])
{
    std::vector<Test> mydata({ Test(4, 8), Test(5, 3), Test(12, 7), Test(8, 9) });

    for (auto const&y : mydata)
    {
        std::cout << y.first << " / " << y.second << std::endl;
    }

    //need to free vector here or sth?

    return 0;
}

我使用类构造函数来初始化向量。上面的代码是好的还是会导致错误?我应该在程序结束时释放向量吗?

标签: c++memory-leaksstdvector

解决方案


推荐阅读