Convert QVector of QSharedPointer to Qvector of QWeakPointer



  • Hi,

    In an attempt to make use of smart pointers, I have a class that contains a QVector with QSharedPointers. Is there an easy way to convert this vector to a vector of QWeakPointers (instead of one by one)?

    My use case is:
    I have a class that should manage the lifetime of my objects, but calling classes would like to get access to this list of objects and interact with them temporarily as long as the pointers are valid (up-cast to QSharedPointers).


  • Moderators

    QVector<QSharedPointer<Type>> and QVector<QWeakPointer<Type>> are unrelated types so there's no "all at once" conversion.
    But you don't even need an explicit loop to do it, so it's not a hard thing:

    QVector<QSharedPointer<T>> v1 { /* ... */ }
    QVector<QWeakPointer<T>> v2;
    
    v2.reserve(v1.size());
    std::transform(v1.begin(), v1.end(), std::back_inserter(v2), 
                   [](const QSharedPointer<T>& ref) { return ref.toWeakRef(); });


  • Thanks I was expecting as much.
    Also thanks for the code, I will probably replace my foreach with something similar.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.