I am trying to construct a string in C++ as below.
const char *cstring = "abcd";
const string cppstr = string(cstring, cstring + strlen(cstring));
This is working fine and cppstr has the value "abcd" even though it doesn't match with any of the string constructors specified in the standard. Can any one please let me know which constructor of string is invoked in this particular case.
There is a templated constructor that takes as its input two InputIterators. (See the cppreference.org reference, constructor (6)). Raw C++ pointers meet all the requirements of InputIterators (in fact, they're RandomAccessIterators). Therefore, calling
string(cstring, cstring + strlen(cstring)
invokes this constructor. That constructor works by iterating across the range of the elements delineated by the iterator and constructing a string as a copy of those elements.
As a note, you can also just write
const string cppstr{cstring, cstring + strlen(cstring)};
here instead of assigning cppstr a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With