C++: Using Smart Pointers with Arrays

The modern C++ standard libraries, includes smart pointers, which are used to help ensure that programs are free of memory and resource leaks and are exception-safe. All good and sweet, but these structures have a dark little secret.

You may ask yourself how do smart pointers choose between delete and delete[] when deleting the managed object from the memory? Well it’s complicated. You may say that they use template specializations and you are almost right, they do for std::unique_ptr but not for std::shared_ptr. That means it is OK to use an std:unique_ptr<int[]> but it is not OK to use std::shared_ptr<int[]>. The reason for this is best explained by Howard Hinnant  here:

The LWG (Library Working Group of the C++ committee) briefly considered the possibility but the idea wasn’t without controversy. Though the controversy was mainly about a feature added to the shared_ptr<T[]> proposal that could have been jettisoned (arithmetic on shared_ptr<T[]>).

But ultimately the real reason is that though it was discussed, there was never an actual written proposal in front of the LWG to do this. It never bubbled up anyone’s priority list (including my own) sufficiently to put the time into writing a proposal.

Informal conversations have recently begun anew on this topic among a few LWG members, and I have personally prototyped it. But there is still no written proposal for it. I think it would be a decent additional tool in the toolbox. Whether it will ever actually happen or not is anyone’s guess.


Array support for shared_ptr now has a draft TS:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s