The copy constructor looks like this:
basic_string(const basic_string& str);
It initializes a new string
object using a string
argument:
string mel("I'm ok!");
string ida(mel);
Here, ida
would get a copy of the string managed by mel
.
The next constructor additionally requires that you specify an allocator:
basic_string(const basic_string& str, const Allocator&);
The following relationships hold after either of these two constructors is called:
• The data()
method returns a pointer to an allocated copy of the array whose first element is pointed to by str.data()
.
• The size()
method returns the value of str.size()
.
• The capacity()
method returns a value at least as large as size()
.
Moving along, the next constructor lets you set several items:
basic_string(const basic_string& str, size_type pos, size_type n = npos,
const Allocator& a = Allocator());
The second argument pos
specifies a location in the source string from which to begin the copying:
string att("Telephone home.");
string et(att, 4);
Position numbers begin with 0
, so position 4
is the p
character. Thus, et
is initialized to "phone home."
.
The optional third argument n
specifies the maximum number of characters to copy. Thus, this initializes pt
to the string "phone"
:
string att("Telephone home.");
string pt(att, 4, 5);
However, this constructor does not go past the end of the source string; for example, the following stops after copying the period:
string pt(att, 4, 200)
Thus, the constructor actually copies a number of characters equal to the lesser of n
and str.size() - pos
.
This constructor requires that pos <= str.size()
—that is, that the initial position copied to is inside the source string; if this is not the case, the constructor throws an out_of_range
exception. Otherwise, if copy_len
represents the lesser of n
and str.size() - pos
, the following relationships hold after the constructor is called:
• The data()
method returns a pointer to a copy of copy_len
elements copied from the string str
, starting with position pos
in str
.
• The size()
method returns copy_len
.
• The capacity()
method returns a value at least as large as size()
.
13.58.209.201