c++ - 带有 vector 的新运算符

标签 c++ vector new-operator operator-keyword

这些问题相对简单。使用 vector 时,是否应该在推回新元素时使用 new 运算符?我应该调用哪种释放方法?这就是我的意思:

// Release method: 1.
void ReleaseMethodOne( vector< int * > &ThisVector )
{
    // Clear out the vector.
    ThisVector.clear( );
    return;
}

// Release method: 2.
void ReleaseMethodTwo( vector< int * > &ThisVector )
{
    // Clear out the vector.
    for( unsigned uIndex( 0 ); uIndex < ThisVector.size( ); uIndex++ )
    {
        delete ThisVector.at( uIndex );
    }
    return;
}

int main( )
{
    vector< int * > Vector;

    // Add a new element.
    Vector.push_back( new int( 2 ) );

    // More code...

    // Free the elements before exiting. Which method should I call here?
    ReleaseMethodOne( Vector ); // This one?
    ReleaseMethodTwo( Vector ); // Or this one?

    return 0;
}

我不久前开始学习 vector ,我学习的书上说 vector 的 clear( ) 方法调用了每个元素的析构函数。这适用于 new 运算符吗?

最佳答案

STL 容器存储您提供给它们的对象的拷贝,在您的示例中是指针。它们永远不会释放显式分配的任何内存。您必须自己释放该内存,因此应使用第二种“释放”方法。

当然,你不需要new每个int .只需使用 vector<int>相反 - 您根本不需要处理手动内存管理。

关于c++ - 带有 vector 的新运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799470/

相关文章:

c++ - 如何将 vector 的单元格传递给 C++ 中的函数?

c++ - 在 C++ 中打印来自多个 vector 的第一个值

c++ - 访问传递给 new[] C++ 的数字

c++ - new Object() 和 Object() 有什么区别

c++ - 这个链表的实现有什么问题?

c++ - Linux 中 system() 调用的问题

c++ - QTreeWidget通过一个函数传递多个项目(多个选择)

c++ - delete 和 delete[] 的确切行为是什么?

c++ - C/C++如何复制结构?

c++ - OpenCV QT,显示视频帧(不使用While循环)