Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: std::unique_ptr<> for arrays

21 views
Skip to first unread message

Alf P. Steinbach

unread,
Aug 11, 2015, 8:48:20 AM8/11/15
to
On 10-Aug-15 11:33 PM, joe...@gmail.com wrote:
> I have a third party library that returns a pointer that the caller is then responsible for:
>
> float* myData = thirdParty.getData();
> delete [] myData;
>
> I liked using boost instead to wrap this into a smart pointer (e.g. scoped_array).
>
> With C++11, I had thought to use unique_ptr, but the deleter on unique_ptr is calling
> the standard delete, not array delete, even though the "new" underneath is allocating
> an array explicitly.

No, it doesn't do that.

Your code should look like this:

unique_ptr<float[]> data( thirdParty.getData() );

Was it?


[snip]
> int main
> {
> std::unique_ptr<float> (goo()); // Calls wrong deleter
> }

Oh, it wasn't.

Well then.

---

Additional info:

The deleter of unique_ptr is customizable in two ways:

* By specializing default_delete (or whatever it was called) for a type.

* By providing a deleter argument to the constructor.

It's worth having in mind that with unique_ptr, as opposed to
shared_ptr, a deleter is not stored with type erasure, and so effective
casts of a unique_ptr can cause a custom deleter to be called with
incorrect pointer value, due to static_cast changing the address.

Cheers & hth.,

- Alf

--
Using Thunderbird as Usenet client, Eternal September as NNTP server.
0 new messages