Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Welcome Guest | Log In | Register | Benefits
Channels ▼
RSS

Design

C++11: unique_ptr



Related Reading


More Insights




CedricWehrum

unique_ptr::get() is probably not only necessary for legacy code. I haven't figured out how to use polymorphism without unique_ptr::get()

I mean this kind of stuff:
Base* b ( /*init*/ );
( (Derived*) b )->only_in_Derived();

Is only possible with unique_ptr in the following way:
unique_ptr<base> ( /*init*/ );
( (Derived*) b.get() )->only_in_Derived();

Note that this doesn't invalidate the uniqueness of the pointer.

PatrickN927

it's still fuzzy to me why unique_ptr can work with stl while auto_ptr cannot. Some say that it works because unique_ptr has the move semantic but from what I understand, in the move semantic, the original pointer will be set to null once it has been moved to the other side, so imagine in the generic sort, how it would work when it needs to create a pivot knowing that the element that it creates from will be gone. Someone please shed some lights? Thanks

Jmeshka

The extra pointer dereference is due to passing the unique_ptr by reference to the function. In many use cases there will be zero additional overhead.

ChrisM080

RIAA is something else (and it's not pretty). I'm pretty sure he meant RAII.

ingomueller.net

I think that the assembly code comparison is not fair. The unique pointer gets passed by reference, which needs to be dereferenced before access. Pass either both arguments as reference or both arguments as value to make the comparison fair...

robhz

It is not quite correct to say that with unique_ptr the access to the object cannot be shared anymore.
First because it can be shared through raw pointers obtained with the get() member function. But in this case one has to ensure that these pointers won't be used after the object is destroyed ( dangling pointers )
Second because it can be converted into shared_ptr if necessary. But in this case the original unique_ptr will be invalidaded (set to NULL). And it can't be converted back to a unique_ptr.

The unique_ptr would be the perfect candidate to be the pointer returned by a factory, for example. The caller may convert it into another kind of pointer if he needs, or just stay with the fast and lightweight unique_ptr otherwise.

AnkurVarsheny

Don't get sold so easily.
with unique_ptr it would mean you can't share you pointers with anyone and only one can reference it at one time. It seems very stupid and under thought implementation

mskelton068

I believe the idiom is Resource Acquisition Is Initialization (RAII), unless there's some new acronym I'm unaware of?