views:

1029

answers:

4

In actual C++ standard creating collections satisfying following rules is hard if not impossible:

  1. exception safety,
  2. cheap internal operations (in actual STL containers: the operations are copies),
  3. automatic memory management.

To satisfy (1) a collection can't store raw pointers. To satisfy (2) a collection must store raw pointers. To satisfy (3) a collection must store objects by value.

Conclusion: the three items collide with each other

Item (2) will not be satisfied when shared_ptrs are used because when a collection will need to move an element, it will need to make two calls, to constructor and destructor. No massive, memcpy()-like copy/move operations are possible.

Am I correct that described problem will be solved by unique_ptr and std::move()? Collection utilizing the tools will be able to satisfy all 3 conditions:

  1. When a collection will be deleted as a side effect of an exception, it will call unique_ptrs' destructors. No memory leak.
    • Unique_ptr does not need any extra space for reference counter; therefore its body should be exact the same size, as wrapped pointer,
    • I am not sure, but it looks like this allows to move groups of unique_ptrs by using memmove() like operations (?),
    • even if it's not possible, the std::move() operator will allow to move each unique_ptr object without making the constructor/destructor pair calls.
  2. Unique_ptr will have exclusive ownership of given memory. No accidental memory leaks will be possible.

Is it true? What are other advantages of using unique_ptr?

+2  A: 

Yes, you are right. I would only add this is possible thanks to r-value references.

Suma
+1  A: 

I agree entirely. There's at last a natural way of handling heap allocated objects.

In answer to:

I am not sure, but it looks like this allows to move groups of unique_ptrs by using memmove() like operations,

there was a proposal to allow this, but it hasn't made it into the draft.

James Hopkin
+1  A: 

It looks like the three conditions I've enumerated in my post are possible to obtain by using Boost Pointer Container Library.

A: 

This question illlustrates why I so love the Bohem garbage collector (libgc). There's never a need to copy anything for reasons of memory management, and indeed, ownership of memory no longer needs to be mentioned as part of APIs. You have to buy a little more RAM to get the same CPU performance, but you save hundreds of hours of programmers' time. You decide.

Norman Ramsey
The pause times on Boehm GC are horrible. Even Java is better.
Zifre