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
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist