What is the correct way to use auto_ptr for dynamically allocated arrays?

If I use auto_ptr to store a pointer to a dynamically allocated array when auto_ptr is killed, it will use the usual delete operation , not delete [] , thus deleting the selected array.

How can I (correctly) use auto_ptr for dynamically allocated arrays?

If this is not possible, is there another smart pointer alternative for dynamically allocated arrays?

Thanks in advance.

+3
source share
5 answers

boost :: shared_array is what you are looking for.

EDIT:

boost, std::vector, , . , shared_array.

, auto_ptr, shared_array. std::vector, , auto_ptr.

+5

. std::auto_ptr .

new[] delete[]. std::vector. Stroustrup.

, , , () . :

std::vector<char> buf(size);
fgets(&buf[0], buf.size(), stdin);

, ++ 11 ( ) buf.data() &buf[0]; buf.data() .

+10

(.. boost), . delete[]. auto_ptr<Wrapper> delete , .

+1

boost boost::scoped_array, boost:: shared_array, std::auto_ptr . . ++ 0x std::unique_ptr, delete [], , , .

+1

The proper way to use auto_ptr (with a dynamically allocated array or whatever) is to use something else. Either boost :: shared_array, or shared_ptr> or shared_ptr> from TR1 in your case. In general, shared_ptr or unique_ptr are smart pointers that are actually smart. Stop using auto_ptr.

0
source

Source: https://habr.com/ru/post/1747911/


All Articles