简体   繁体   中英

Warning C4267 in Visual Studio: 'argument': conversion from 'size_t' to 'const _Elem', possible loss of data

I am getting the warning from this function:

std::pair<size_t, size_t> GetSection(const string& s1, const string& s2) {
        size_t top_section = s1.find(s2 + ":");
        size_t bottom_section = s1.find(s1.length() - top_section);

        return std::make_pair(top_section, bottom_section);
}

I don't understand what conversion is occurring that is causing the problem. I also understand that this function can be written like so:

    std::pair<size_t, size_t> GetSection(const string& s1, const string& s2) {
        size_t top_section = s1.find(s2 + ":");
        size_t bottom_section = top_section + s2.length() + 1;

        return std::make_pair(top_section, bottom_section);
}

I just want to know why I am getting this warning.

The problem is in this function call:

s1.find(s1.length() - top_section);

The argument s1.length() - top_section is a number of type size_t , but the find method is supposed to take in a string or character to search for.

(Specifically, because C++ always assumes you mean what you say, it's trying to convert the size_t to a char , but that causes a loss of precision since the char type is only 8 bits wide.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM