[017]string Class Usage precautions

Source: Internet
Author: User

Recently wrote a play, wrote a function like this:

void foo (conststring& iStr) {    for (int0; I < Istr.length (); + +i)        {string str = istr.at (i);    }}

The other business involved in the middle of the function, the problem is that after writing the above code, compile it.

At first glance, isn't that normal? Get a value in the ISTR and assign it to Str.

Actually, because usually we use the string with the habit, will habitually think it is the basic type, but, it is the class type Ah!

So, when we take the following actions:

string str = istr.at (i);

istr.at (i) returns a const char character, so when the instance is STR, it will find out if there is a copy constructor of the const char type in the string.

As a result, there is no way to copy the object, it is wrong.

void foo (conststring& iStr) {    for (int0; I < Istr.length (); + +i)        {constchar str = istr.at (i);    }}

This will be no problem.

What if we must use the string type? This can be done by using string to preserve the principle of characters

void foo (conststring& iStr) {    string  str;      for (int0; i < istr.length (); + +i)        {= istr.at (i);    }}

Separating the object instance from the assignment does not occur.

[017]string Class Usage precautions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.