简体   繁体   中英

QSharedPointer from a raw pointer

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

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

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.

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