C++ static_cast
型別轉換:C v.s. C++
C語言裡的型別轉換在C++中被分成了 static_cast
, dynamic_cast
, const_cast
及reinterpret_cast
等四種不同的方式,這是為了確保在不同的情況下,型別轉換的代碼都能work as expected。
static_cast
implicit conversion sequence from expression to new_type
static_cast
可用於implicit conversion,而根據Implicit conversions,numeric promotion屬於implicit conversion。所謂的numeric promotion,指的是:
prvalues of small integral types (such as char) may be converted to
prvalues of larger integral types (such as int).
也就是將佔用byte數較少的型別轉換為佔用byte數較多的型別。
在TensorRT/blob/master/samples/common/buffers.h
內BufferManager
的建構子中,使用static_cast
將int
型別的變數轉為size_t
型別:
int mBatchSize;
static_cast<size_t>(mBatchSize);
我們知道int
型別佔用4 bytes。那麼size_t
呢?摘自About size_t and ptrdiff_t,size_t
型別在不同作業系統上的大小為:
On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.
在32-bit系統上佔4 bytes,在64-bit系統上佔8 bytes。
所以將int
轉為size_t
屬於numeric promotion,因此也是implicit conversion,所以是在static_cast
的適用範圍內。
參考連結
Why use static_cast(x) instead of (int)x?
static_cast in C++ | Type Casting operators
C++四种类型转换运算符:static_cast、dynamic_cast、const_cast和reinterpret_cast