0

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?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Vij
  • 27
  • 1
  • 7

1 Answers1

3

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;
}
ltc
  • 3,313
  • 1
  • 28
  • 26