简体   繁体   中英

std::size_t vs size_t vs std::string::size_type

  • Where does size_t come from when I don't have anything included?
  • Is it reasonable to always assume size_t == std::size_t ?
  • When should I use the size_type in std containers ( string::size_type , vector<T>::size_type , etc)?

Where does size_t come from when I don't have anything included in an empty project?

If you don't have anything included, then you can't use size_t . It's defined in <stddef.h> (and perhaps also in <cstddef> , if your version of that header puts the definitions in the global namespace as well as std ).

Is it reasonable to always assume size_t == std::size_t?

Yes. All types and functions defined by the C library are included in the std namespace, as long as you include the appropriate C++ header (eg <cstddef> rather than <stddef.h> )

When should I use std:: _ ::size_type?

Do you mean the size_type types defined in some standard classes and templates such as vector ? You could use those when using those classes if you like. In most cases, you'll know that it's the same as size_t , so you might as well use that and save a bit of typing. If you're writing generic code, where you don't know what the class is, then it's better to use size_type in case it's not compatible with size_t .

For example, you might want to write a container designed to hold more items than can be represented by size_t . You might use some kind of big number type to represent the container's size, which isn't convertible to size_t . In that case, code like size_t s = c.size() would fail to compile - you'd need to use Container::size_type instead.

Where does size_t come from when I don't have anything included in an empty project?

size_t is a base unsigned integer memsize-type defined in the standard library of C/C++ languages. It is defined in "stddef.h" for C and in <cstddef> for C++ .

Types defined by the header file "stddef.h" are located in the global namespace while <cstddef> header places the size_t type in the namespace std .

"stddef.h" from C is included into C++ for compatibility, and hence the type can be found in both the global namespace ( ::size_t ) and the std namespace ( std::size_t ).

size_t<cstddef>定义,位于std命名空间中。

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