Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which std::string constructor is being called here?

Tags:

c++

string

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.

like image 723
kadina Avatar asked May 24 '26 04:05

kadina


1 Answers

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.

like image 79
templatetypedef Avatar answered May 26 '26 17:05

templatetypedef