validity of begin() on empty string or vector

O

Old Wolf

Is this undefined behaviour:

#include <string>
#include <vector>
#include <algorithm>

int main()
{
std::string s;
char buf[20];

std::copy(s.begin(), s.end(), buf);
}

Same question again for std::vector<char> instead of std::string.

Do I have to go s.empty() before every time I go s.begin(), in
case begin() is undefined?
 
D

Dietmar Kuehl

Old said:
Is this undefined behaviour:
std::string s;
char buf[20];

std::copy(s.begin(), s.end(), buf);

No, why should it? It is an empty sequence. This applies to all
container types which can be empty as well. Of course, you cannot
dereference the the past the end iterator which is in this case
identical to 'begin()' but this is not done by 'std::copy()' or
other standard algorithms taking an input sequence.
 
K

Kristo

Old said:
Is this undefined behaviour:

#include <string>
#include <vector>
#include <algorithm>

int main()
{
std::string s;
char buf[20];

std::copy(s.begin(), s.end(), buf);
}

It's only undefined if s.size() is greater than 20, in which case you'd
overflow the buffer. Also note that buf will not be usable as a C-style
string after the call to std::copy(). To use it as such you'll have to
append a null character yourself.

Kristo
 
C

Clark S. Cox III

Is this undefined behaviour:

#include <string>
#include <vector>
#include <algorithm>

int main()
{
std::string s;
char buf[20];

std::copy(s.begin(), s.end(), buf);
}

Same question again for std::vector<char> instead of std::string.

Do I have to go s.empty() before every time I go s.begin(), in
case begin() is undefined?

No. If the container is empty, then begin() and end() return iterators
to the same location. Which means that they are valid in the sense that
they are non-singular, they simply cannot be dereferenced.

There is nothing undefined about the code you posted (of course, it
doesn't really do anything, but that's beside the point).
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top