views:

265

answers:

2

I used to write code like this:

class P {};

class Q: public P {};

class A {
    // takes ownership
    A(P* p): p_(p) {}

    scoped_ptr<P> p_;
};

A a(new Q);

With C++0x, should I rewrite class A as:

class A {
    // takes ownership
    A(unique_ptr<P>&& p): p_(move(p)) {}

    unique_ptr<P> p_;
};
+2  A: 

IMO it is better to use unique_ptr as it provides an additional feature: move semantics. i.e. you can write a move constructor, etc for your class, unlike scoped_ptr. Also, unique_ptr doesn't have an overhead associated with it as it is the case with scoped_ptr, so it is a superior facility. A decision of a rewrite is up to you of course, in case you don't need move semantics then there is no point of the rewrite. Don't forget that unique_ptr is from the standard library, so it must be provided with any compliant implementation of C++0x(when it becomes reality of course :)!

AraK
`scoped_ptr` does not incur overhead. You're probably thinking of `shared_ptr` :)
Billy ONeal
@Billy ONeal Sometimes I don't know how to express something in English :) Basically, I wanted to say, both don't create overhead.
AraK
If they both don't create overhead, then why is one "superior" compared to the other? (Referencing -> "doesn't have an overhead associated with it as it is the case with scoped_ptr, so it is a **superior** facility")
Billy ONeal
@Bily ONeal **move semantics**
AraK
+1  A: 

I have to disagree with AraK on one being superior. There is no such thing as a superior choice between the two as it often depends on usage. That's like saying a SmartCar is superior to a pick-up truck for all uses because it's lighter and faster. In reality, sometimes you need a truck and sometimes you don't. Your choice of pointer should be based on what you need.

The nice thing about scoped_ptr is it adds a level of safety. By using scoped_ptr you are delcaring that the memory created will exist only for that scope and no more, thus you get compile-time protection against attempting to move it or transfer it.

So, if you want to create somethign but limit it's scope, used scoped_ptr. If you want to create something and have ownership be movable, use unique_ptr. If you want to create something and share that pointer and cleanup when all referencers are gone, use shared_ptr.

James Michael Hare
Sorry, but this is dead wrong. The biggest problem is that `unique_ptr` is in the standard, while `scoped_ptr` is not. Therefore, if a C++0x compiler is suitable for your application, you should always use `unique_ptr`.
Billy ONeal