4

I currently have something like this:

QSharedPointer<t> Qsharedfoo;

Now I have a raw pointer to foo as well called rawfoo. How can I make foo point own the raw pointer and start pointing to it. I know in boost with shared pointers we could use boost::make_shared how do we do it with QSharedPointer ?

I want to do something like this:

Qsharedfoo = rawfoo
demonplus
  • 5,613
  • 12
  • 49
  • 68
MistyD
  • 16,373
  • 40
  • 138
  • 240

2 Answers2

6

Straight from the Qt documentation, we have something like this:

QSharedPointer<MyObject> obj = QSharedPointer<MyObject>(new MyObject);

You can basically pass your pointer in the same fashion:

// Here I assume that T is the class you're using for Qsharedfoo.
QSharedPointer<T> Qsharedfoo = QSharedPointer<T>(rawfoo);
Son-Huy Pham
  • 1,899
  • 18
  • 19
3

How can I make foo point own the raw pointer and start pointing to it. I know in boost with shared pointers we could use boost::make_shared how do we do it with QSharedPointer ?

You cannot, unfortunately.

  • You will always need to go through the constructor unlike make_shared.

  • It is not necessarily exception safe.

In summary, you would need to go through the constructor and operator= as follows:

Qsharedfoo = QSharedPointer<T>(rawfoo); // operator=() overload

or if you already have a reference to a pointer, then use the reset() method as follows:

Qsharedfoo.reset(rawFoo);

But as mentioned in the beginning, these are not equal operations to what you are looking for.

László Papp
  • 51,870
  • 39
  • 111
  • 135
  • Much like the old std::auto_ptr, I too prefer to use reset() to avoid the slight overhead you mentioned. But it appears that I may have misunderstood what MistyD really wanted to have answered. – Son-Huy Pham Jan 11 '14 at 00:55