By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,983 Members | 1,717 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,983 IT Pros & Developers. It's quick & easy.

is assigning a substr to the parent str OK?

P: n/a
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

Apr 10 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
David Resnick wrote:
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 10 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.