简体   繁体   中英

c++: Casting void pointer to shared_ptr

I'm implementing(overriding) the index function in a QAbstractItemModel derived class, qt treeview MV, where a cast to pointer looks like:

TreeItem* parentItem = static_cast<TreeItem*>(parent.internalPointer());

Where internalPointer is void *QModelIndex::internalPointer() const

How should I change the code to cast the void pointer coming from parent.internalPointer() to std::shard_ptr<TreeItem> ?


Since you say shared_ptr is supposed to take ownership of the pointer ( delete it automatically), you want this:

std::shared_ptr<TreeItem> parentItem(static_cast<TreeItem *>(parent.internalPointer()));

Or, to assign to an existing shared_ptr :

parentItem = std::shared_ptr<TreeItem>(static_cast<TreeItem *>(parent.internalPointer()));

or

parentItem.reset(static_cast<TreeItem *>(parent.internalPointer());

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