Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use std::size_t all over the place? [duplicate]

Possible Duplicate:
When to use std::size_t?

I have a lot of constants in my code that are unsigned numbers, e.g. counters, frequency cutoffs, lengths, etc. I started using std::size_t for all of these, instead of int or unsigned int.

Is that the right thing to do? I started it because the STL containers use it for their sizes, it's used for string position, etc.

like image 375
Frank Avatar asked Jun 06 '10 22:06

Frank


2 Answers

std::size_t is the type to use for counting memory locations, like array lengths, the size of objects, etc. STL containers are using container_type::size_type, which will usually map to std::size_t, but isn't guaranteed to do so.

If you need types for holding non-negative integrals which are not used for the above mentioned purposes, what's wrong with unsigned short, unsigned int, and unsigned long?

like image 111
sbi Avatar answered Oct 12 '22 03:10

sbi


size_t is actually a typedef defined in stddef.h and it's platform dependent, so you can't really make any assumptions about it. On gcc 4.4 (i486) it's defined as a long unsigned int, unless the OS already defines it, so for instance on Free BSD 5 on a i386 machine it's gonna be unsigned int whilst on a ia64 machine it's gonna be a unsigned long. So for instance if you try to do something like

size_t i;
...
char buf[4];
sprintf(buf,"%u",i);

Sometimes it's gonna run, but on some platforms/compilers you're gonna get a buffer overflow.

My point is that this can cause some nasty portability issues if you have to make assumptions about the size/type of size_t.

like image 3
Radu Chivu Avatar answered Oct 12 '22 03:10

Radu Chivu