Guide
shared_ptr
Prior to C++17
, shared_ptr
could not be used to manage dynamically allocated arrays. By default, shared_ptr
will call delete
on the managed object when no more references remain to it. However, when you allocate using new[]
you need to call delete[]
, and not delete
, to free the resource.
In order to correctly use shared_ptr
with an array, you must supply a custom deleter.
code example
1 | //OK, pointer to int 999 |
std::unique_ptr<int[]>
has built-in support for arrays to properlydelete[]
.
image buffer
1 | std::shared_ptr<uchar> pImage(new uchar[length], std::default_delete<uchar[]>()); |
Reference
History
- 20191012: created.