QSharedPointer from a raw pointer

3.7k Views Asked by At

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
2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

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);