std::string substr() question

B

Boltar

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
 
J

Joe Greer

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
 
B

Boltar

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top