0

I have two classes. In the class A constructor, I am calling the constructor of class B. However, while creating class B object, I want to pass the QSCOPED pointer of the class A object. In short, instead of this pointer, I want to pass the QSCOPED pointer. How can I do so?

class B;
class A
{

 class A();

};

A::A()
{
  QScopedPointer<B> m_p_B( new B(this));
}

My requirement is that instead of passing this pointer, I want to pass the QSCOPED pointer of the class A. Basically a QSCOPED pointer of this pointer. How can I do so?

ebarr
  • 7,166
  • 1
  • 22
  • 37
dexterous
  • 5,684
  • 9
  • 42
  • 84
  • please paste a definition of B class – 4pie0 Mar 27 '14 at 09:06
  • You say you want to pass the QSCOPED pointer of the class `A` object - does that mean that the instance of `A` was created as a `QScopedPointer`? (That is, was the instance represented by `this` created by `QScopedPointer(new A())`?) – Lilshieste Mar 27 '14 at 15:27

1 Answers1

1

Something like this:

It's not needed to pass QScopedPointer in the constructor, it will be created in the initializer list.

#include<QScopedPointer>

class B
{
public:
    B(A* a) : ma(a) {}

private:
    QScopedPointer<A> ma;
}
Ferenc Deak
  • 30,889
  • 14
  • 82
  • 151
  • This could be a really dangerous move, since we don't have any knowledge of who "owns" the `A` resource. 1) If the instance was created via `new`, then this is ok (if the owner doesn't call `delete`); 2) If the instance was created via `new`, but already wrapped in a `QScopedPointer`, then this will result in a [double delete](http://stackoverflow.com/questions/9169774/what-happens-in-a-double-delete "Question: What happens in a double delete?"); 3) If the instance was created on the stack, this will lead to undefined behavior – Lilshieste Mar 27 '14 at 15:55
  • @Lilshieste you're right, I have totally ignored this side of the story. I assumed that if there is a request to wrap A in a scoped pointer all these 1) 2) 3) are taken care of. – Ferenc Deak Mar 27 '14 at 20:27