Dea*_*tor 4 c++ vector new-operator operator-keyword
这些问题相对简单.使用向量时,我应该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;
}
我不久前开始学习矢量,我正在学习的那本书说,矢量的clear( )方法称为每个元素析构函数.这适用于new运营商吗?
该clear方法确实会调用析构函数.但是,你的向量存储指针,指针的析构函数是一个简单的无操作.它没有打电话delete.
因此,简单地调用clear不会释放int您分配的所有对象的内存new.你需要delete他们.
如果使用智能指针而不是普通指针,则指向对象将在适当的时间释放,而不必执行任何特殊操作.
STL容器存储您提供给它们的对象的副本,示例中的指针.它们永远不会释放您明确分配的内存.你必须自己解除内存,所以应该使用第二个"发布"方法.
当然,你不需要new每一个人int.只需使用vector<int>- 您根本不必处理手动内存管理.