开发者

Qsharedpointer class

I am trying to use a smart pointer class in the following way

class A 
{

 friend  class B;
virtual methods ();

protec开发者_如何学Goted:
virtual ~classA();

}

class B:public QSharedPointer<class A>
{
  class B();
~ class B();

}

I plan to replace occurrences of Class A* with class B. Is this approach correct?


No this is not really the way to do this. It looks like your design goal here is to make it impossible for someone to allocate an object of type A without putting it in a smart pointer. The normal way to do this is not to inherit from the smart pointer, but to make your type have

  1. A private constructor
  2. A private destructor
  3. A public static factory method returning in this case QSharedPointer
  4. A private deleter class that is a friend of class A

Here is an example using boost::shared_ptr (I do not have a QT installation right now, but you should be able to just replace all instances of boost::shared_ptr with QSharedPointer)

#include <boost/shared_ptr.hpp>

class A {
private:
    A() {}
    ~A() {}


    struct deleter {
            void operator()(A* val) {delete val;}
    };
    friend class deleter;
public:
    static boost::shared_ptr<A> create() {
            return boost::shared_ptr<A>(new A(), A::deleter());
    }

};

int main()
{
    //A a1;                //compile error
    //A *a2 = new A();     //compile error
    boost::shared_ptr<A> a3 = A::create();

    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜