简体   繁体   中英

Qsharedpointer class

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

class A 
{

 friend  class B;
virtual methods ();

protected:
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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM