Smart D-Ptr in KCoreAddons

Mark markg85 at gmail.com
Fri Aug 23 13:24:36 UTC 2013


On Fri, Aug 23, 2013 at 8:49 AM, Ivan Čukić <ivan.cukic at kde.org> wrote:
>
>> The paper that describes make_unique - and contains an implementation
>> - can be found here [1]. For reference, the full code to have
>> make_unique ready to paste in any file is here [2].
>
> Make unique is only a method to create a std::unique_ptr, and it doesn't
> provide (or, rather, inhibit) the features d_ptr does. Namely, d_ptr uses
> unique_ptr for most of its logic, but makes the interface to the class slimmed
> down and safer - tailored exactly for this case.
>
> It removes:
>  - modifiers
>  - get() and friends
>  - operator bool
>  - operator*
>  - comparison operators
>  - possibility to be null
>
> It mostly makes the interface and behaviour look as if it was no pointer at
> all, apart from accessing members with d->.
>
>> P1 - safety: no access to the raw pointer
>> P2 - safety: no accidental initialization errors or anything similar
>> P3 - safety: no possible leaks
>> P4 - convenience: forwarded constructor arguments (': d(1,2)' instead of ':
>>    d(new Private(1,2))')
>> P5 - convenience: default constructor works for no-arg Private constructor
>>    (nothing instead of 'd(new Private())')
>> P6 - convenience: no delete d;
>> P7 - they are spiffy (Aaron)
>
> std::unique_ptr with make_unique does not provide P1, P2, P5 and P4.
> For P4, you would need to write d(make_unique<Private>(...)) in order for it
> to work instead of d(...), which is not much cleaner than d(new Private(...)).
>
>
> Cheerio,
> Ivan

P1, P2 are your preference. Why do you even need to care about access
to the raw pointer. The d_ptr/make_unique pointer is stored as private
class member anyway. I don't see the need for those but that might
also be because i just don't know enough in that area. If you could
explain that, that would be welcome.

P4 is again a matter of taste. Even in your d_ptr you still have to do
d_ptr<Private> on the header side, only the cpp side is more clean
with d_ptr. however, does that matter much? I think the best way to go
here i making a "d_ptr" template that uses make_unique to combine the
shortness of your code. But that is _way_ above my knowledge level.

P5 make_unique<Private>() works as well, right?


More information about the Kde-frameworks-devel mailing list