Qt Containers, Implicit Sharing and Passing Parameters



  • Greetings.

    I've been reading about Qt Containers and Implicit Sharing and emerged me a question about passing parameters of Qt Containers. In particular, I wonder:

    Is it worth using references when I pass Qt Containers by parameters or the Implicit Sharing mechanism makes this unnecessary?

    For efficiency (prevent copying) I always use references (constant or not, as appropriate) to objects passed by parameters. Then by example, with Qt Containers... Which is better:

    Use 'const QList< MyObject >&' or simply 'QList< MyObject >'?

    Thanks in advance for any reply or comment.


  • Moderators

    Hi,

    Const references are still recommended.

    Implicit sharing makes it cheap to create copies, but it's still not free.



  • Thanks for your answer JKSH.

    And in the case of functions that return Qt Containers... Is it better to use references?


  • Moderators

    You're welcome :)

    It is usually dangerous to return references, because the original might be modified (or even destroyed). Your should return copies.

    Example: The reference returned by badFunc() will become invalid when the function returns, because the original string gets destroyed:
    @
    // Wrong:
    const QString& badFunc() {
    QString str = "Hello World!"
    return str;
    }

    // Right:
    QString goodFunc() {
    QString str = "Hello World!"
    return str;
    }
    @



  • Thanks again JKSH.

    bq. It is usually dangerous to return references, because the original might be modified (or even destroyed). Your should return copies.

    The issue is that my program return a reference to a member (one QList of pointers to a QGraphicsItem subclass) of a own custom class.

    Given what you've described so far, I think in this case, return a reference would be more efficient... since due to the mechanism of Implicit Sharing, return a copy of the member would end up being the same.

    Am I right?


  • Moderators

    [quote author="IsaacEnrique" date="1422460420"]Given what you've described so far, I think in this case, return a reference would be more efficient... since due to the mechanism of Implicit Sharing, return a copy of the member would end up being the same.

    Am I right?[/quote]Possibly. I don't know if you'll be able to detect any improvement. (You can try to measure it -- that's the only way to tell if something is more efficient)



  • Well, I guess I'll have to try to measure it.

    Thanks for everything.


Log in to reply
 

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