Re: Behaviour of string(const char* str, size_t len) when str is the null pointer
apm35@student.open.ac.uk wrote:
kanze wrote:
apm35@student.open.ac.uk wrote:
Obviously when len is zero the empty string should result. But
might not the implementation peek inside the buffer pointed to
by str no matter what the value of len is?
It can't. Only the first length characters starting with the
pointer are accessible.
Indeed. That was my point. If the code does peek then when the pointer
is null the behaviour is undefined.
I think you have the meaning of 'undefined' wrong. 'undefined', in the
context of C++, means that the standard explicitly says that the behaviour
is undefined. It only means that it explicitly doesn't require any
behaviour from an implementation.
In this case, the 'undefined' starts with passing a null pointer to the
string's ctor, because the standard explicitly mentions the precondition
that ptr!=0. It has nothing to do with possible dereferenciation of a null
pointer - if that happens is up to the implementation. However, it is
undefined behaviour even if the implementation did not peek at the memory
but only because the standard says so, and that is what you should avoid at
all costs.
BTW: if you were using STLport in its diagnostic mode, it would tell you
that this precondition was violated.
No. You have it backwards. You have undefined behavior because
you have violated a pre-condition.
Armed with the relevant section of the std to quote, this is what I now
want to go and tell the author of this code.
In my prerelease copy of the standard it is in 21.3.1, basic_string
constructors. It say there:
| basic_string( const charT* s, size_type n,
| const Allocator& a = Allocator());
|
| Requires:
| s shall not be a null pointer and n < npos.
|
Uli
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]