string - "" + something in C++ -
string - "" + something in C++ -
i've been having freaky stuff happening in code. believe have tracked downwards part labeled "here" (code simplified, of course):
std::string func() { char c; // stuff assign c homecoming "" + c; // here }
all sorts of stuff happen when seek cout
result of function. think i've managed pieces of underlying c++ documentation, , many segmentation fault. it's clear me doesn't work in c++ (i've resorted using stringstream
conversions string
now), know why. after using lots of c# quite while , no c++, has caused me lot of pain.
""
string literal. have type array of n const char
. particular string literal array of 1 const char
, 1 element beingness null terminator.
arrays decay pointers first element, e.g. in expressions pointer required.
lhs + rhs
not defined arrays lhs
, integers rhs
. defined pointers lhs , integers rhs, usual pointer arithmetic.
char
integral info type in (i.e., treated integer by) c++ core language.
==> string literal +
character hence interpreted pointer +
integer.
the look "" + c
equivalent to:
static char const lit[1] = {'\0'}; char const* p = &lit[0]; p + c // "" + c equivalent look
you homecoming std::string
. look "" + c
yields pointer const char
. constructor of std::string
expects const char*
expects pointer null-terminated character array.
if c != 0
, look "" + c
leads undefined behaviour:
for c > 1
, pointer arithmetic produces undefined behaviour. pointer arithmetic defined on arrays, , if result element of same array.
if char
signed, c < 0
produces undefined behaviour same reason.
for c == 1
, pointer arithmetic does not produce undefined behaviour. that's special case; pointing 1 element past lastly element of array allowed (it not allowed utilize points to, though). still leads undefined behaviour since std::string
constructor called here requires argument pointer valid array (and null-terminated string). one-past-the-last element not part of array itself. violating requirement leads ub.
what happens constructor of std::string
tries determine size of null-terminated string passed it, searching (first) character in array equal '\0'
:
string(char const* p) { // simplified char const* end = p; while(*end != '\0') ++end; //... }
this either produce access violation, or string creates contains "garbage". possible compiler assumes undefined behaviour never happen, , funny optimizations result in weird behaviour.
by way, clang++3.5 emits nice warning snippet:
warning: adding 'char' string not append string [-wstring-plus-int]
return "" + c; // here ~~~^~~
note: utilize array indexing quiet warning
c++ string
Comments
Post a Comment