is assigning a substr to the parent str OK?

D

David Resnick

Is the assignment of a substr of the string 'a' to 'a' in the
code below OK?

#include <string>
#include <iostream>

int main(void)
{
std::string a = "hello";
std::cout << a << std::endl;

a = a.substr(0,2);
std::cout << a << std::endl;

return 0;
}

I saw no restrictions on operator= in my STL reference (Josuttis).
But this makes me slightly nervous. I've programmed more in C
than C++, and this feels like it could be rather like an overlapping
strcpy (or multiple modifications of an object without intervening
sequence point). This code works, and valgrind doesn't complain, but
I'd
still like to know if it is guaranteed to be correct usage.

Thanks,

-David
 
V

Victor Bazarov

David said:
Is the assignment of a substr of the string 'a' to 'a' in the
code below OK?
Yes.

#include <string>
#include <iostream>

int main(void)
{
std::string a = "hello";
std::cout << a << std::endl;

a = a.substr(0,2);
std::cout << a << std::endl;

return 0;
}

I saw no restrictions on operator= in my STL reference (Josuttis).
But this makes me slightly nervous. I've programmed more in C
than C++, and this feels like it could be rather like an overlapping
strcpy (or multiple modifications of an object without intervening
sequence point). This code works, and valgrind doesn't complain, but
I'd
still like to know if it is guaranteed to be correct usage.

Expression 'a.substr(0,2)' creates a temporary object, which then is
assigned to 'a'. No problem whatsoever.

V
 

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

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top