Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Implicit Sharing



  • Hi friends, I have read that implicit sharing is a clever methodology in saving resources. In that case, Can any one please explain how I can verify two QString objects in which one is allocated with some data and the other one is assigned with the former one.

    Say
    QString a="aaa"
    QString b=a;//shallow copy
    qDebug()<<a.toStdString().c_str();//0x100
    qDebug()<<b.toStdString().c_str();//0x101
    Why do I get two different pointer addresses if shallow copy was being done?


  • Lifetime Qt Champion

    Hi,

    Because toStdString returns a std::string and c_str() returns the address of the first char from that std::string object.

    Note that calling it the way you do, will also get you different values for different calls because of the lifetime of the objects involved.

    In any case, the pointer you are getting has just no relation with the original QString objects.


  • Lifetime Qt Champion

    Hi,

    Because toStdString returns a std::string and c_str() returns the address of the first char from that std::string object.

    Note that calling it the way you do, will also get you different values for different calls because of the lifetime of the objects involved.

    In any case, the pointer you are getting has just no relation with the original QString objects.



  • Is there no way of knowing that both are pointing to same content? So it is a bad practice to use toStdString() over and over for the same variable.Isn't it?


  • Qt Champions 2019

    @prinzkm said in Implicit Sharing:

    So it is a bad practice to use toStdString() over and over for the same variable.Isn't it?

    Yes. You can assign what toStdString() returns to a variable instead of calling it over and over.



  • I found the answer :) . isSharedWith() function returns true if two implicitly shared objects are pointing to the same.
    ie a.isSharedWith(b) returns true in my case.This will remain true until either of it is modified.


Log in to reply