std::string substr() question

Discussion in 'C++' started by Boltar, Apr 16, 2008.

  1. Boltar

    Boltar Guest

    How persistant is the string created by substr()? Is it deleted
    immediately the context exits or is it stored internally by the parent
    string? I ask because I'm wondering if its safe to keep a copy of the
    pointer returned doing mystr.substr(...).c_str() for a short while to
    do some processing on it. Obviously if the sub string is deleted it'll
    become invalid.

    Thanks for any help

    B2003
     
    Boltar, Apr 16, 2008
    #1
    1. Advertising

  2. Boltar

    Joe Greer Guest

    Boltar <> wrote in news:af321295-9a52-4276-bb7e-
    :

    > How persistant is the string created by substr()? Is it deleted
    > immediately the context exits or is it stored internally by the parent
    > string? I ask because I'm wondering if its safe to keep a copy of the
    > pointer returned doing mystr.substr(...).c_str() for a short while to
    > do some processing on it. Obviously if the sub string is deleted it'll
    > become invalid.
    >


    Instead of worrying about it, I encourage you to look at the various
    constructors for string and the assign method as well. Both of them allow
    the same operations as substr and you don't have to worry about any
    lifetime issues you might with temporaries. These have become second
    nature to me these days because it directly specifies what I want to do and
    doesn't require the compiler to be hyper-intelligent to avoid extra copies.

    joe
     
    Joe Greer, Apr 16, 2008
    #2
    1. Advertising

  3. Boltar

    Boltar Guest

    On Apr 16, 2:18 pm, Joe Greer <> wrote:
    > Instead of worrying about it, I encourage you to look at the various
    > constructors for string and the assign method as well. Both of them allow
    > the same operations as substr and you don't have to worry about any
    > lifetime issues you might with temporaries. These have become second
    > nature to me these days because it directly specifies what I want to do and
    > doesn't require the compiler to be hyper-intelligent to avoid extra copies.


    Sounds like a good idea, I'll give that a try.

    B2003
     
    Boltar, Apr 16, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Jansson
    Replies:
    5
    Views:
    6,318
    Ivan Vecerina
    Mar 17, 2005
  2. Fei Liu
    Replies:
    9
    Views:
    447
  3. sks

    String - substr query

    sks, Jul 12, 2006, in forum: C++
    Replies:
    6
    Views:
    432
  4. Alien
    Replies:
    5
    Views:
    567
    Pete Becker
    Sep 18, 2006
  5. Jeffrey Walton
    Replies:
    10
    Views:
    944
    Mathias Gaunard
    Nov 26, 2006
Loading...

Share This Page