Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Strange behavior of .toStdString()

Strange behavior of .toStdString()

Scheduled Pinned Locked Moved Solved General and Desktop
3 Posts 2 Posters 826 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    HaHoHSO
    wrote on last edited by
    #1

    Hi all,

    I just came across the following subtlety: The code

    QString a("121");

    std::string s = a.toStdString();
    const char* p = s.c_str();
    const char* q = a.toStdString().c_str();

    for (int i = 0; i < 4; i++) std::cout << (int)p[i] << " "; std::cout << std::endl;
    for (int i = 0; i < 4; i++) std::cout << (int)q[i] << " "; std::cout << std::endl;

    results in

    49 50 49 0
    0 50 49 0

    Why does the first byte differs depending on using .toStdString() and .c_str() in one resp. two different lines?

    Thanks a lot in advance!

    1 Reply Last reply
    0
    • VRoninV Offline
      VRoninV Offline
      VRonin
      wrote on last edited by
      #2

      because accessing q is undefined behaviour.
      a.toStdString() returns a temporary (std::string) object, you take its address and then the object gets deleted.

      It's equivalent to:

      const char* q;
      {
      std::string p = a.toStdString();
      q = p.c_str();
      }

      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
      ~Napoleon Bonaparte

      On a crusade to banish setIndexWidget() from the holy land of Qt

      1 Reply Last reply
      5
      • H Offline
        H Offline
        HaHoHSO
        wrote on last edited by
        #3

        Got it! Thanks a lot!

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved