【问题标题】:Will I get a memory leak if I set an existing vector = vector<int>(num)?如果我设置一个现有的 vector = vector<int>(num),我会出现内存泄漏吗?
【发布时间】:2014-12-26 22:36:52
【问题描述】:

如果我在 C++ 中执行以下操作会发生什么:

vector<int> vect;
vect = vector<int>(8);
vect = vector<int>(3);

在第二行分配的八个整数会在最后一行被删除,还是会保留分配但丢失? (即内存泄漏)

【问题讨论】:

  • 内部发生自动动态内存分配和删除。 STL 库为您处理一切。所以没有内存泄漏,除非 STL 库中存在错误;)

标签: c++ vector memory-leaks


【解决方案1】:

不,没有内存泄漏。像所有精心设计的资源管理类一样,vector 重载了它的赋值运算符来做正确的事情。

它要么重用它的内存;要么或释放它并分配一个新块;或者,使用移动语义,释放它并从分配的临时向量中获取内存。

【讨论】:

  • 好的,非常感谢!所以我只需要在使用 malloc 或“new”时小心,对吗?
  • @PaoloErdman:是的。通常你可以避免这种麻烦;使用容器和智能指针为您完成所有繁琐的内存管理。
【解决方案2】:

按照标准规定

23.2.3 Sequence containers [sequence.reqmts]
Table 100
a = il; X& Requires: T is CopyInsertable into X and
                     CopyAssignable. Assigns the range
                     [il.begin(),il.end()) into a. All existing
                     elements of a are either assigned to or
                     destroyed.
                     Returns: *this.

因此,我们可以得出结论,不会有任何内存泄漏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2017-02-19
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2016-05-01
    相关资源
    最近更新 更多