Ostrzeżenie kompilatora (poziom 3) C4267

"var" : konwersja z "size_t" na "typ", możliwa utrata danych

Uwagi

Kompilator wykrył konwersję z size_t na mniejszy typ, która może spowodować obcięcie wartości.

Aby naprawić to ostrzeżenie, użyj polecenia size_t zamiast type. Alternatywnie należy użyć typu całkowitego, który może reprezentować pełny zakres size_t na platformie docelowej. Jeśli wartość jest znana w czasie kompilacji i pasuje do typu docelowego, kompilator nie generuje tego ostrzeżenia.

Przykład

Poniższy przykład generuje kod C4267.

// C4267.cpp
// compile by using: cl /W4 C4267.cpp
void Func1(short) {}
void Func2(int) {}
void Func3(long) {}
void Func4(size_t) {}

int main() {
   size_t bufferSize = 10;
   Func1(bufferSize);   // C4267 for all platforms
   Func2(bufferSize);   // C4267 only for 64-bit platforms
   Func3(bufferSize);   // C4267 only for 64-bit platforms
   Func4(bufferSize);   // OK for all platforms

   // Because the compiler knows the value of bufferSize_const at compile time (because it's const),
   // it knows that converting it to short can't truncate the value so no warning is emitted
   const size_t bufferSize_const = 10;
   Func1(bufferSize_const); // No C4267

   // Because the compiler knows the value of bufferSize_big_const is 0x10000 at compile time
   // (because its const), it knows it doesn't fit in short, but does fit in int.
   const size_t bufferSize_big_const = 0x10000;
   Func1(bufferSize_big_const); // C4267
   Func2(bufferSize_big_const); // No C4267

   return 0;
}