devxlogo

Never Store Arrays of Objects in an auto_ptr

Never Store Arrays of Objects in an auto_ptr

The Standard Library’s auto_ptr class template automatically destroys an object that is allocated on the free store when the current scope is exited. For example:

 #include  //definition of auto_ptr#include using namespace std;int main(){  auto_ptr ps (new string);  *ps = "hello";} //ps is automatically destroyed at this point

Note however, that using auto_ptr to for an array of objects results in undefined behavior because the destructor of auto_ptr calls plain delete (and never delete []) to destroy its bound object. As you know, only operator delete[] should be used in order to destroy an array of dynamically-allocated objects. Therefore, never store arrays of objects in an auto_ptr:

 int main(){  auto_ptr ps (new string[2]); //bad} //undefined behavior

devx-admin

Share the Post: