这些问题相对简单。使用 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/